【问题标题】:How to concataecance object array values of duplicates如何连接重复的对象数组值
【发布时间】:2021-06-11 12:46:05
【问题描述】:

我有一个包含重复的id 属性的对象,我想将它们减少为每个数组。我只是想出了一种方法来找到唯一的ids,但是如何连接name 属性?

const x = [
   {id: 1, name: 'green'},
   {id: 2, name: 'red'},
   {id: 1, name: 'blue'}
]

想要的结果:

[
   {id: 1, name: 'green, blue'},
   {id: 2, name: 'red'}
]

【问题讨论】:

    标签: javascript arrays object ecmascript-6 filter


    【解决方案1】:

    简单的 reduce 组合并使用 Object.values 来获得你想要的结果。

    const x = [{
        id: 1,
        name: 'green'
      },
      {
        id: 2,
        name: 'red'
      },
      {
        id: 1,
        name: 'blue'
      }
    ]
    
    const result = Object.values(x.reduce((acc, obj) => {
      if (acc[obj.id]) {
        acc[obj.id].name += ", " + obj.name;
      } else {
        acc[obj.id] = { ...obj
        };
      }
      return acc;
    }, {}));
    
    console.log(result);

    【讨论】:

      【解决方案2】:
      1. 使用.reduce 遍历x,同时使用Mapid 存储为key,并将数组元素存储为value
      2. 如果map 已经有与此id 的记录,只需将名称连接到它即可
      3. 否则,向其中添加新记录
      4. 最后,mapvalues 将包含由id 分组的所有数组元素,并且name 包含所有这些元素。

      const x = [ { id: 1, name: 'green' }, { id: 2, name: 'red' }, { id: 1, name: 'blue' }
      ];
      
      const res = [...x.reduce((map, {id, name}) => {
        if(map.has(id)) map.get(id).name += `, ${name}`;
        else map.set(id, { id, name });
        return map;
      }, new Map)
      .values()
      ];
      
      console.log(res);

      【讨论】:

        【解决方案3】:

        使用Set 获取unique ids 列表的简单解决方案。

        然后,使用filtermap 我们得到所有匹配的对象,以及join 的名称。

        const x = [
           {id: 1, name: 'green'},
           {id: 2, name: 'red'},
           {id: 1, name: 'blue'}
        ]
        
        const result = [];
        const uniqueIds = [...new Set(x.map(item => item.id))];
        const merged = uniqueIds.forEach((id) => {
          
          // Matching ids
          const match = x.filter((o) => o.id === id);
          
          // Names of matching ids
          const names =  match.map(x => x.name);
          
          // Add new
          result.push({
            id,
            names: names.join(', ')
          });
        });
        
        console.log(result);

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-11-24
          • 2020-02-02
          • 1970-01-01
          • 1970-01-01
          • 2020-12-04
          • 2020-09-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多