您好,我有一个带有对象和数组对象值的 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: []}, ]}
2 回答
智慧大石
TA贡献1946条经验 获得超3个赞
let skuSet = {};
for (let i = 0; i < test.sku.length; i++) {
if (!skuSet[test.sku[i].id]) {
skuSet[test.sku[i].id] = test.sku[i];
}
}
for (let i = 0; i < test_2.panels.length; i++) {
let current = test_2.panels[i];
for (let j = 0; j < current.feature.length; j++) {
if (skuSet[current.feature[j]]){
current.feature[j] = skuSet[current.feature[j]];
}
}
}
console.log(JSON.stringify(test_2));
如果您对上述逻辑有任何疑问,请告诉我。
德玛西亚99
TA贡献1770条经验 获得超3个赞
let skuMap = {}; test.sku.map((skuData) => { skuMap[skuData.id] = skuData }) test_2.panels.map((panelData) => { panelData.feature = panelData.feature.map((panelFeatureId) => skuMap[panelFeatureId]) })
添加回答
举报
0/150
提交
取消