第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

javascript 將多個JSON對象合并成一個(帶子父關(guān)系)

javascript 將多個JSON對象合并成一個(帶子父關(guān)系)

慕姐4208626 2018-11-28 14:13:41
1、目前有一個很任性的接口API,它提供的數(shù)據(jù)非常不合理2、數(shù)據(jù)如下3、我想將它們合并成一個json如下:是否有好的辦法?
查看完整描述

1 回答

?
慕田峪4524236

TA貢獻(xiàn)1875條經(jīng)驗 獲得超5個贊

額,就是不想寫循環(huán)


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重構(gòu)下:


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));


查看完整回答
反對 回復(fù) 2018-12-28
  • 1 回答
  • 0 關(guān)注
  • 910 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號