javascript - 如何合并数组里某个key值一样的对象,合并后把不相同的值放到一个数组
问题描述
初始时var old = [
{ id: 1, name: 'first'},{ id: 2, name: 'first'},{ id: 3, name: 'second'},{ id: 4, name: 'second'}
]希望得到的结果var new = [
{ a: [1, 2], b: 'first'},{ a: [3, 4], b: 'second'}
]
问题解答
回答1:供参考
var new = Array.from( old.reduce((dict, item)=> { if (dict.has(item.name)) { dict.get(item.name).push(item.id) } else { dict.set(item.name, [item.id]) } return dict }, new Map())).map(item => ({a: item[1], b: item[0]}))回答2:
原数组是
var old = [ {id: 1,name: 'first' }, {id: 2,name: 'first' }, {id: 3,name: 'second' }, {id: 4,name: 'second' }]
期望得到
new = [ {a: [1, 2],b: 'first' }, {a: [3, 4],b: 'second' }]实现
var getNew = old => { let temp = old.reduce((acc, cur) => {if (acc[cur.name]){ acc[cur.name].push(cur.id); } else { acc[cur.name] = [cur.id]}return acc; }, {});return Object.keys(temp).map(key => {return { a: temp[key], b: key} })}
Just Run getNew(old)