我必须数组,我想通过相同的 id 将它们合并到一个数组中。所以每两个具有相同 id 的数组应该合并
案例1:
{
"id":1212,
"instructor":"william",
...
}
案例2:
[
{
"id":1212,
"name":"accounting",
...
},
{
"id":1212,
"name":"finance",
...
}
]
我需要的结果是:
{
"id": 1212,
"instructor": "william",
"Courses": [
{
"id":1212,
"name":"accounting",
...
},
{
"id":1212,
"name":"finance",
...
}
]
}
最佳答案
您要求的不是合并,但这是您可以做到这一点的方法。
const instructors = [{ "id":1212, "instructor":"william", }];
const courses = [
{ "id":1212, "name":"accounting" },
{ "id":1212, "name":"finance" }
];
const expected = [{ "id":1212, "instructor":"william", "courses": [
{ "id":1212, "name":"accounting" },
{ "id":1212, "name":"finance" }
]}];
const composed = instructors.map(ins => {
const ret = {...ins};
ret.courses = courses.filter(cou => cou.id === ins.id);
return ret;
});
console.log(composed);
关于javascript - 合并两个 json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51673093/