javascript - 创建一个新数组,计算某个参数在数组中出现的次数
问题描述
我有一个数组,它提供了一些包含产品数据的额外参数。我为此重新创建了一个简单的版本,如下所示:
{
title: 'hello',
description: 'world'
tags: [{id: 1, tagName: 'prices'}, {id: 2, tagName: 'video'}]
},
{
title: 'hello',
description: 'world'
tags: [{id: 3, tagName: 'images'}, {id: 2, tagName: 'video'}]
},
{
title: 'hello',
description: 'world'
tags: [{id: 2, tagName: 'video'}, {id: 4, tagName: 'site'}, {id: 6, tagName: 'online'}]
}
]
我数组中的每个对象都有一个名为“标签”的数组。我必须创建一个新数组来查看该数组并计算某个标签在产品上使用的次数,以便我可以创建如下所示的结果:
[
{
id: 1,
amount: 1
},
{
id: 2,
amount: 3
},
{
id: 3,
amount: 1
},
{
id: 4,
amount: 1
},
{
id: 6,
amount: 1
}
]
到目前为止我所做的是创建一个空数组并开始循环遍历产品数组。然后我检查是否在我的新数组中找到了 tag.id,如果没有......然后将其添加到数组中。如果循环会再次找到相同的 Id,而不是向数组添加新项目,它应该将数量增加 1。
到目前为止,我认为我真的过度设计它,因为我无法让它正常工作。也许这里有人可以帮助我提供一些我可以使用的代码?
谢谢!
解决方案
您可以使用Map Object来计算标签。
const data = [
{
title: 'hello',
description: 'world',
tags: [
{ id: 1, tagName: 'prices' },
{ id: 2, tagName: 'video' },
],
},
{
title: 'hello',
description: 'world',
tags: [
{ id: 3, tagName: 'images' },
{ id: 2, tagName: 'video' },
],
},
{
title: 'hello',
description: 'world',
tags: [
{ id: 2, tagName: 'video' },
{ id: 4, tagName: 'site' },
{ id: 6, tagName: 'online' },
],
},
];
const map = new Map();
data.forEach(({ tags }) => {
tags.forEach(({ id }) => {
const key = id;
if (map.has(key))
map.set(key, { ...map.get(key), amount: map.get(key).amount + 1 });
else map.set(key, { id, amount: 1 });
});
});
const ret = [...map.values()];
console.log(ret);
推荐阅读
- c# - 使用 mimekit 解密带有附件的电子邮件
- r - 将 splice() 的输出保存到文本文件
- node.js - MongoDB不更新
- install4j - 任务管理器中的 2 个安装程序进程
- python - 使用用户输入选择要修改的变量?
- docker - 每当 docker hub 上有新的 alpine 的 python 补丁版本可用时,如何配置dependabot.yml 进行更新?
- python - 如何在Python中散点图二维数组
- postgresql - Postgresql 12 通过运行分析修复了 Slave 上的高 CPU 峰值。无法进行 RCA
- python - 避免 IndexError : 列表索引超出范围
- javascript - 使用正则表达式删除外部脚本标签