为了减少发送到客户端的有效负载,我的其余 api 仅返回子实体的 id,如下所示:
[
{
"id":369,
"name":"Harlequin Enterprises Ltd",
"description":"Buford Konopelski",
"parent":{
"id":323
}
},
{
"id":323,
"name":"Heyday Books",
"description":"Zola Rutherford",
"parent":{
"id":3
}
},
{
"id":3,
"name":"Happy House",
"description":"Mrs. Dwight Mohr",
"parent":{
"id":null
}
}
]
是否有任何库可以帮助我将所有实体加入/合并到此中:
[
{
"id":369,
"name":"Harlequin Enterprises Ltd",
"description":"Buford Konopelski",
"parent":{
"id":323,
"name":"Heyday Books",
"description":"Zola Rutherford",
"parent":{
"id":3,
"name":"Happy House",
"description":"Mrs. Dwight Mohr",
"parent":{
"id":null
}
}
}
},
{
"id":323,
"name":"Heyday Books",
"description":"Zola Rutherford",
"parent":{
"id":3,
"name":"Happy House",
"description":"Mrs. Dwight Mohr",
"parent":{
"id":null
}
}
},
{
"id":3,
"name":"Happy House",
"description":"Mrs. Dwight Mohr",
"parent":{
"id":null
}
}
]
//这是一个受 IVO GELOV 解决方案启发的简化解决方案:
var mapID = inputJSON.map((item) => item.id);
// attach parents to childreen
var normalized = inputJSON.map((item) =>
{
var parentIndex = mapID.indexOf(item.parent.id);
item.parent = inputJSON[parentIndex];
return item;
});
console.log(JSON.stringify(normalized))
最佳答案
你必须使用 map
var inputJSON, mapID = {};
// create the map - allowing to get an item by ID
inputJSON.forEach((item) =>
{
mapID[item.id] = item;
});
// attach parents to childreen
inputJSON.forEach((item) =>
{
if(item.parent && item.parent.id && mapID[item.parent.id])
{
item.parent = mapID[item.parent.id]
}
});
关于javascript - 如何加入/合并 json 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51378941/