2 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超10個(gè)贊
您可以創(chuàng)建一個(gè)組合嵌套對(duì)象的函數(shù)。然后使用map()和find()創(chuàng)建對(duì)象的組合數(shù)組。
var products = [
{
Id: 1,
Name: 'Product1',
Attributes: {
Storage: 'Normal',
Size: 'Small'
}
},
{
Id: 2,
Name: 'Product2',
Attributes: {
Storage: 'Normal',
Size: 'Small'
}
}
];
var newData = [
{
Id: 2,
Name: 'French Fries'
},
{
Id: 1,
Attributes: {
Size: 'Medium'
}
}
];
const haveNested = obj => Object.values(obj).some(x => typeof x === "object");
function combine(obj1,obj2){
if(!haveNested(obj1)) return ({...obj1,...obj2})
let res = obj1
for(let key in obj1){
if(typeof obj1[key] === "object"){
res[key] = combine(obj1[key],obj2[key]);
}
else if(obj2[key]) res[key] = obj2[key]
}
return res;
}
const result = products.map(x => {
let temp = newData.find(a => a.Id === x.Id);
return temp ? combine(x,temp) : x;
})
console.log(result)
添加回答
舉報(bào)