我有一个数组,提供了一些包含产品数据的额外参数。我为此重新创建了一个简单的版本,如下所示:
{
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
}
]
到目前为止,我所做的是创建一个空数组并开始遍历product数组。然后,我检查是否在新数组中找到了tag.id,如果没有,则将其添加到数组中。如果循环会再次找到相同的ID,则无需将新项添加到数组中,而应将值增加1。
到目前为止,我认为我真的对它进行了过度设计,因为我无法使其正常工作。也许这里有人可以帮我一些我可以使用的代码?
谢谢!
可能有更快的方法,但这是一种方法:
const original = [
{
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'}]
}
];
let tags = [];
original.forEach(e => {
e.tags.forEach(t => {
let match = tags.find(tag => tag.id == t.id);
if (match) {
match.amount++;
} else {
tags.push({id: t.id, amount: 1});
}
});
});
console.log(tags);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句