1 回答

TA贡献1875条经验 获得超5个赞
额,就是不想写循环
let json2Obj = json2.reduce((acc, cur) => {
let childId = cur.childId;
if (!acc[childId]) {
acc[childId] = [];
}
acc[childId].push(cur);
return acc;
}, {})
json1.forEach(item => {
item.childchild = json2Obj[item.childId]
})
let json1Obj = json1.reduce((acc, cur) => {
let mainId = cur.mainId;
if (!acc[mainId]) {
acc[mainId] = [];
}
acc[mainId].push(cur);
return acc;
}, {})
json.forEach(item => {
item.child = json1Obj[item.mainId];
})
console.log(JSON.stringify(json));
reduce重构下:
const toObj = (json, idStr) => json.reduce((acc, cur) => {
let id = cur[idStr];
if (!acc[id]) {
acc[id] = [];
}
acc[id].push(cur);
return acc;
}, {})
const json2Obj = toObj(json2, 'childId');
json1.forEach(item => item.childchild = json2Obj[item.childId])
const json1Obj = toObj(json1, 'mainId');
json.forEach(item => item.child = json1Obj[item.mainId])
console.log(JSON.stringify(json));
添加回答
举报