Group Array with count

前端 未结 3 479
醉酒成梦
醉酒成梦 2021-01-15 08:19

I have an array of items that contains several properties. One of the properties is an array of tags. What is the best way of getting all the tags used in those items and or

3条回答
  •  别那么骄傲
    2021-01-15 08:58

    You can do this simply using a reduce operation. For example

    var items = [{
      itemName: 'item1',
      tags: [
        {id: 'tag1', name: 'Tag 1'},
        {id: 'tag2', name: 'Tag 2'}
      ]
    }, {
      itemName: 'item2',
      tags: [
        {id: 'tag1', name: 'Tag 1'},
        {id: 'tag3', name: 'Tag 3'}
      ]
    }];
    
    var tags = items.reduce((tags, item) => {
      item.tags.forEach(tag => {
        tags[tag.id] = tags[tag.id] || 0;
        tags[tag.id]++;
      });
      return tags;
    }, {});
    
    document.write('
    ' + JSON.stringify(tags, null, '  ') + '
    ');

提交回复
热议问题