var arr = [{ key: 1, name: 2, job: 3
}, { key: 1, name: 22, job: 33
}, { key: 2, name: 222, job: 333
}, { key: 2, name: 2222, job: 3333
}];arr 这个数组有多个字段,我想根据key这个字段相同的属性的时候,就进行合并。最终想实现的结果如arr2 arr2 = [{ key: 1, info: [{ name: 2, job: 3
}, { name: 22, job: 33
}]
}, { key: 2, info: [{ name: 222, job: 333
}, { name: 2222, job: 3333
}]
}];
2 回答
万千封印
TA贡献1891条经验 获得超3个赞
var keys = Array.from(new Set(arr.map(o=>o.key)));var result = keys.map(key=>{ return {key: key, info: arr.filter(o=>o.key==key).map(o=>({name:o.name, job:o.job})) } });console.log(result);
牧羊人nacy
TA贡献1862条经验 获得超7个赞
function mergeKey(arr) { const keyMap = arr.reduce((r, item)=>{ const newItem = {...item}; delete newItem.key; r[item.key] = (r[item.key] || []).concat(newItem); return r; } , {}); return Object.keys(keyMap).map(key=>({ key, info: keyMap[key], })); } mergeKey(arr)
添加回答
举报
0/150
提交
取消