javascript - 如何根据对象属性对对象数组进行分组?
问题描述
我有一个如下所示的数组:
let data:[
{
"class": "X",
"student":[
{
"name": "Bumblebee",
"id":"SAB77"
}
]
},
{
"class": "X",
"student":[
{
"name": "Omega",
"id":"SAB78"
}
]
},
{
"class": "IX",
"student":[
{
"name": "Pluto",
"id":"RBC17"
}
]
},
{
"class": "IX",
"student":[
{
"name":"16 psyche",
"id":"RBC18"
}
]
}
]
我想分组如下:
data:[
{
"class": "X",
"student":[
{
"name": "Bumblebee",
"id":"SAB77"
},
{
"name": "Omega",
"id":"SAB78"
}
]
},
{
"class": "IX",
"student":[
{
"name": "Pluto",
"id":"RBC17"
},
{
"name": "16 psyche",
"id":"RBC18"
}
]
}
]
解决方案
let data = [{
"class": "X",
"student": [{
"name": "Bumblebee",
"id": "SAB77"
}]
},
{
"class": "X",
"student": [{
"name": "Omega",
"id": "SAB78"
}]
},
{
"class": "IX",
"student": [{
"name": "Pluto",
"id": "RBC17"
}]
},
{
"class": "IX",
"student": [{
"name": "16 psyche",
"id": "RBC18"
}]
}
];
const result = data.reduce((acc, obj) => {
let existedObj = acc.length && acc.find(ele => ele.class === obj.class);
if (!acc.length || !existedObj) {
acc.push(obj);
return acc;
}
existedObj.student = [...existedObj.student, ...obj.student];
return acc;
}, []);
console.log(result);
推荐阅读
- debugging - 如何在 Common LISP 上使用 Emacs 内置调试器查看局部变量?
- rust - 错误:在实例化 `func::<[closure]>` 时达到递归限制
- jquery - 无需重新加载的 Ajax ResponseText
- javascript - 如果 Blob URL 是不可变的,Media Source Extension API 如何使用它们来流式传输视频?
- javascript - 如何检查对象中是否存在相同的字符串?
- node.js - 如何计算 mongodb 集合中特定字段的实例
- javascript - 谁能帮我创建一个不允许顶级导航的 iframe?
- php - XAMPP 调用未定义的函数
- sql - 如何在 AdonisJS 中捕获迁移中的 SQL 错误
- java - 递归斐波那契方法的记忆不是更快吗?