对象操作,唯一 ID,具有组合值如何

Object Manipulation, unique ids, with combined values how to

使用下面的数据,我试图找出如何组合 ID、return 和它们的数组键

// example data
var data = [
   { id: 1, key: 'a' },
   { id: 1, key: 'b' },
   { id: 2, key: 'c' },
   { id: 3, key: 'a' },
   { id: 3, key: 'b' },
   { id: 3, key: 'c' }
];

我尝试了以下方法来减少

data.reduce((id, curr) => {
   id[curr.id] = [...id[curr.id] || [], curr]
   return id
}, {});

// results
{
   '1': [ { id: 1, key: 'a' }, { id: 1, key: 'b' } ],
   '2': [ { id: 2, key: 'c' } ],
   '3': [ { id: 3, key: 'a' }, { id: 3, key: 'b' }, { id: 3, key: 'c' } ]
}

如何才能return这种格式的数据

{ id: 1, key: ['a','b'] }, 
{ id: 2, key: ['c'] },
{ id: 3, key: ['a','b','c'] }

这是你的算法:

data.reduce(( sets, item ) => {
    let extantItem = sets.find(set => set.id === item.id)
    
    if(extantItem) {
        extantItem.key.push(item.key)
    } else {
        extantItem = { id: item.id, key: [item.key] }
        sets.push(extantItem)
    }
    
    return sets
}, [])

您可以使用 Map Object with Array.prototype.reduce() 方法。

const data = [
  { id: 1, key: 'a' },
  { id: 1, key: 'b' },
  { id: 2, key: 'c' },
  { id: 3, key: 'a' },
  { id: 3, key: 'b' },
  { id: 3, key: 'c' },
];

const ret = [
  ...data
    .reduce(
      (map, { id, key }) =>
        map.set(
          id,
          map.has(id)
            ? { id, key: [...map.get(id).key, key] }
            : { id, key: [key] }
        ),
      new Map()
    )
    .values(),
];
console.log(ret);