1、目前有一个很任性的接口API,它提供的数据非常不合理
2、数据如下
var json = [{ "mainId": 1, "title": "abc", "createdate": "2017-06-28" }, { "mainId": 2, "title": "ddddd", "createdate": "2017-06-25" }]; var json1 = [{ "childId": 1, "mainId": 1, "childname": "cname" }, { "childId": 2, "mainId": 1, "childname": "cname2" }, { "childId": 3, "mainId": 2, "childname": "cname3" }, { "childId": 4, "mainId": 2, "childname": "cname4" }]; var json2 = [{ "childchildId": 1, "childId": 1, "childname": "cname" }, { "childchildId": 2, "childId": 1, "childname": "cname2" }, { "childchildId": 3, "childId": 2, "childname": "cname3" }, { "childchildId": 4, "childId": 2, "childname": "cname4" }, { "childchildId": 5, "childId": 3, "childname": "cname" }, { "childchildId": 6, "childId": 3, "childname": "cname2" }, { "childchildId": 7, "childId": 4, "childname": "cname3" }, { "childchildId": 8, "childId": 4, "childname": "cname4" }];3、我想将它们合并成一个json如下:
var result = [{ "mainId": 1, "title": "abc", "createdate": "2017-06-28", child: [{ "childId": 1, "mainId": 1, "childname": "cname", childchild: [{ "childchildId": 1, "childId": 1, "childname": "cname" }, { "childchildId": 2, "childId": 1, "childname": "cname2" }] }, { "childId": 2, "mainId": 1, "childname": "cname2", childchild: [{ "childchildId": 3, "childId": 2, "childname": "cname3" }, { "childchildId": 4, "childId": 2, "childname": "cname4" }] }]方式一
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));