如何使用数组中嵌套的另一个对象的数据更新对象?

所以我需要编写一个函数,用另一个对象更新我的对象(但该对象位于数组内),例如:

  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};

最好的方法是什么?


一只斗牛犬
浏览 95回答 3
3回答

慕盖茨4494581

您可以简单地循环遍历数组并将数组对象分布在 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)

holdtom

这可以用一行完成: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)

慕的地6264312

我认为这就是你想要的。获取 中的每一项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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript