我有以下数组
array1 = [{
category: "Age"
id: "11"
},
{
category: "Gender"
id: "M"
},
{
category: "Age"
id: "23"
},
{
category: "Gender"
id: "F"
},
{
category: "Education"
id: "Graduate"
},
{
category: "Age"
id: "55"
}
]
我希望它按类别分组,类似这样
groupedArray = [{
category: "Age",
groupedCat: [{
category: "Age"
id: "11"
},
{
category: "Age"
id: "23"
},
{
category: "Age"
id: "55"
}
],
category: "Gender",
groupedCat: [{
category: "Gender"
id: "M"
},
{
category: "Gender"
id: "F"
}
],
category: "Education",
groupedCat: [{
category: "Education"
id: "Graduate"
}]
}]
答案 0 :(得分:0)
您可以这样做:
var array1 = [{
category: "Age",
id: "11"
}, {
category: "Gender",
id: "M"
}, {
category: "Age",
id: "23"
}, {
category: "Gender",
id: "F"
}, {
category: "Education",
id: "Graduate"
}, {
category: "Age",
id: "55"
}];
let res = {};
for (var o of array1) {
if (res[o.category] === undefined) {
res[o.category] = [];
}
res[o.category].push(o);
}
console.log(res);
请注意,这与您在上面的问题中所要求的不完全相同,我改用category
作为对象的键。我认为这就是您要寻找的。如果没有发表评论,我可以更新。
希望这会有所帮助