数据数数组如何重新组合?
如果我有一个数据如何:
child:[ {nameB:B1,image:M1},{nameB:B1,image:M2},{nameB:B2,image:M1},{nameB:B1,image:M4} ,{nameB:B2,image:M2} ]
如何可发生成:
child:[ {nameB:B1,image: [ M1,M2,M4 ] } ,{nameB:B2,image:[ M1,M2]} ]
请指教!!!!!!
1 回复
let arr = [
{ nameB: "B1", image: "M1" },
{ nameB: "B1", image: "M2" },
{ nameB: "B2", image: "M1" },
{ nameB: "B1", image: "M4" },
{ nameB: "B2", image: "M2" }
]
const map = new Map();
arr.forEach(item => {
let val = map.get(item.nameB);
if (val) {
let images = [...val];
images.push(item.image);
map.set(item.nameB, images)
} else {
map.set(item.nameB, [item.image])
}
})
console.log(map);