3 回答

TA貢獻1850條經(jīng)驗 獲得超11個贊
您可以簡單地循環(huán)遍歷數(shù)組并將數(shù)組對象分布在 mazda 對象內(nèi)。這是使用for循環(huán)之后最快的方法。
let mazda = { model: 5, seria: 22, wheels: 4,};
const newItems= [{ LCDscreen: true },{ wheels: 5 },{ model: 6},{ weight: 500},{ mirrors: 4}]
newItems.forEach(item => {
? ? ? mazda = {...mazda, ...item};
});
console.log(mazda)

TA貢獻1805條經(jīng)驗 獲得超10個贊
這可以用一行完成:
newItems.reduce((acc, patch) => Object.assign(acc, patch), mazda)
這會迭代newItems
列表中的所有對象并將它們mazda
一個接一個地合并。
如果您不想mazda
修改對象而是獲取新對象,請使用空對象 ( {}
) 作為第一個參數(shù)Object.assign
:
const newMazda = newItems.reduce((acc, patch) => Object.assign({}, acc, patch), mazda)

TA貢獻1817條經(jīng)驗 獲得超6個贊
我認為這就是你想要的。獲取 中的每一項newList并將其作為新屬性添加到mazda對象中。
const mazda = { model: 5, seria: 22, wheels: 4,};
const newItems= [{ LCDscreen: true },{ wheels: 5 },{ model: 6},{ weight: 500},{ mirrors: 4}]
const result = newItems.reduce( (acc,item) => ({...acc,...item}),mazda);
console.log(result)
添加回答
舉報