首页 > 解决方案 > 创建一个新数组,计算某个参数在数组中出现的次数

问题描述

我有一个数组,它提供了一些包含产品数据的额外参数。我为此重新创建了一个简单的版本,如下所示:

    {
        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。

到目前为止,我认为我真的过度设计它,因为我无法让它正常工作。也许这里有人可以帮助我提供一些我可以使用的代码?

谢谢!

标签: javascriptarraysloopsobject

解决方案


您可以使用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);


推荐阅读