如果对象具有相同的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'}
]
答案 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));
这是更高级的解决方案。这将删除重复项,并对用户进行排序