我有一个这样的对象数组
const obj = [
{
id: 1,
name: "Abc"
},
{
id: 2,
name: "BED"
},
{
id: 1,
name: "FGH"
},
{
id: 3,
name: "RFS"
},
{
id: 1,
name: "Abc"
},
{
id: 2,
name: "BGH"
}
]
我想合并具有相同名称和相同名称的对象,以便我的最终输出看起来像这样-
const result = [
[
{
id: 1,
name: "Abc"
},
{
id: 1,
name: "Abc"
}
],
[
{
id: 1,
name: "TSD"
}
],
[
{
id: 2,
name: "BED"
}
],
[
{
id: 2,
name: "BGH"
}
],
[
{
id: 3,
name: "RFS"
}
]
]
注意-我在数组中大约有300-400个对象,并且使用嵌套的For循环来解决此问题。因此,我正在寻找更好,快速的解决方案
答案 0 :(得分:2)
您可以使用reduce()
并使用对象累加器。最后,使用Object.values
获得一个数组。
const obj = [ { id: 1, name: "Abc" }, { id: 2, name: "BED" }, { id: 1, name: "FGH" }, { id: 3, name: "RFS" }, { id: 1, name: "TSD" }, { id: 2, name: "BGH" } ]
let res = Object.values(obj.reduce((ac,a) => {
if(!ac[a.id]) ac[a.id] = [];
ac[a.id].push(a);
return ac;
},{}))
console.log(res)
for...of
const obj = [ { id: 1, name: "Abc" }, { id: 2, name: "BED" }, { id: 1, name: "FGH" }, { id: 3, name: "RFS" }, { id: 1, name: "TSD" }, { id: 2, name: "BGH" } ]
let res = {};
for(let item of obj){
if(!res[item.id]) res[item.id] = [];
res[item.id].push(item);
}
console.log(Object.values(res))