根据相同的 id 合并数组内的数组对象

您好,我有一个带有对象和数组对象值的 2 个变量,在“test”和“test_2”中,我想根据 id 合并 sku(“test”)和功能(“test_2”)(如下所示) .我正在考虑什么是最好的合并方法,对于 test_2 我将功能转换为值数组对象 ex: feature:[{id:xxx}] 首先,然后我进行合并,因为我尝试它不会不工作。希望这里的任何人都可以帮助我。谢谢


const test = 

    {

        sku: [

            {id:"282828282", link:"ksksks.com"},

            {id:"676867868", link:"lallaa.com"},

            {id:"543454554", link:"sssss.com"},

            {id:"345473663", link:"fdfsas.com"}

        ],

      

    }


const test_2 = 

{

        panels: [

            {id:"9328492847", feature: ['282828282']},

            {id:"6756734535", feature: ['543454554', '282828282']},

            {id:"6545353453", feature: []},

            {id:"4353567688", feature: []},

        ]

}


const test_3 = 

{


        panels: [

            {id:"9328492847", feature: [{id: '282828282', link:"ksksks.com"} ]},

            {id:"6756734535", feature: [{id: '543454554', link:"sssss.com"}, {id:'282828282',link:"ksksks.com"}]},

            {id:"6545353453", feature: []},

            {id:"4353567688", feature: []},

        ]


}


一只萌萌小番薯
浏览 192回答 2
2回答

智慧大石

let skuSet = {};for (let i = 0; i < test.sku.length; i++) {&nbsp; &nbsp; if (!skuSet[test.sku[i].id]) {&nbsp; &nbsp; &nbsp; &nbsp; skuSet[test.sku[i].id] = test.sku[i];&nbsp; &nbsp; }}for (let i = 0; i < test_2.panels.length; i++) {&nbsp; &nbsp; let current = test_2.panels[i];&nbsp; &nbsp; for (let j = 0; j < current.feature.length; j++) {&nbsp; &nbsp; &nbsp; &nbsp; if (skuSet[current.feature[j]]){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; current.feature[j] = skuSet[current.feature[j]];&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}console.log(JSON.stringify(test_2));如果您对上述逻辑有任何疑问,请告诉我。

德玛西亚99

let&nbsp;skuMap&nbsp;=&nbsp;{}; test.sku.map((skuData)&nbsp;=>&nbsp;{&nbsp;skuMap[skuData.id]&nbsp;=&nbsp;skuData&nbsp;}) test_2.panels.map((panelData)&nbsp;=>&nbsp;{ &nbsp;&nbsp;panelData.feature&nbsp;=&nbsp;panelData.feature.map((panelFeatureId)&nbsp;=>&nbsp;skuMap[panelFeatureId]) })
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript