亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

如何使用數組中嵌套的另一個對象的數據更新對象?

如何使用數組中嵌套的另一個對象的數據更新對象?

一只斗牛犬 2023-11-02 17:07:38
所以我需要編寫一個函數,用另一個對象更新我的對象(但該對象位于數組內),例如:  const mazda = { model: 5, seria: 22, wheels: 4,};我想添加來自以下位置的數據:const newItems= [{ LCDscreen: true },{ wheels: 5 },{ model: 6},{ weight: 500},{ mirrors: 4},];但因此第一個對象的序列沒有改變。結果應該是{ seria: 22 ,model: 6, wheels: 4, LCDscreen: true, weight: 500 , mirrors: 4};最好的方法是什么?
查看完整描述

3 回答

?
慕蓋茨4494581

TA貢獻1850條經驗 獲得超11個贊

您可以簡單地循環遍歷數組并將數組對象分布在 mazda 對象內。這是使用for循環之后最快的方法。


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)


查看完整回答
反對 回復 2023-11-02
?
holdtom

TA貢獻1805條經驗 獲得超10個贊

這可以用一行完成:

newItems.reduce((acc, patch) => Object.assign(acc, patch), mazda)

這會迭代newItems列表中的所有對象并將它們mazda一個接一個地合并。

如果您不想mazda修改對象而是獲取新對象,請使用空對象 ( {}) 作為第一個參數Object.assign

const newMazda = newItems.reduce((acc, patch) => Object.assign({}, acc, patch), mazda)


查看完整回答
反對 回復 2023-11-02
?
慕的地6264312

TA貢獻1817條經驗 獲得超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)


查看完整回答
反對 回復 2023-11-02
  • 3 回答
  • 0 關注
  • 208 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號