如何在javascript中彼此添加相同的id对象

时间:2018-10-31 15:27:15

标签: javascript

如果对象具有相同的ID,我会尝试将它们彼此组合。

let obj = 
         [ 
           {id: 1, users: '1,2,3'},
           {id: 1, users: '4,5,6'},
           {id: 2, users: '1,2'},
           {id: 2, users: '3'}
         ]

and I would like to get combined objects with same id.

[ 
  {id: 1, users: '1,2,3,4,5,6'},
  {id: 2, users: '1,2,3'}
]

1 个答案:

答案 0 :(得分:0)

let obj = 
         [ 
           {id: 1, users: '1,2,3'},
           {id: 1, users: '4,5,6'},
           {id: 2, users: '1,2'},
           {id: 2, users: '3'},
           {id: 3, users: '3,2,4'},
           {id: 3, users: '5,1,2'}
         ];
         
const mergeSameIds = obj => (
  obj.reduce( (res, o) => {
    res[o.id] = {
      id: o.id,
      users: !res[o.id] ? o.users : [...new Set(res[o.id].users.split(',').concat(o.users.split(',')))].sort().join(',')
    }
    
    return res;
  }, {} )
  
);

console.log(mergeSameIds(obj));

这是更高级的解决方案。这将删除重复项,并对用户进行排序