javascript 将多个JSON对象合并成一个(带子父关系)

1、目前有一个很任性的接口API,它提供的数据非常不合理
2、数据如下

https://img2.mukewang.com/5c25c7430001c81515740076.jpg

3、我想将它们合并成一个json如下:

https://img2.mukewang.com/5c25c7540001f15d16820077.jpg

是否有好的办法?

慕姐4208626
浏览 878回答 1
1回答

慕田峪4524236

额,就是不想写循环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));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript