简体   繁体   中英

How to update an object with data from another object nested in array?

So i need to write a function which updates my object with another object (but this object is inside an array), for example:

  const mazda = { model: 5, seria: 22, wheels: 4,};

and i want to add data from:

const newItems= [{ LCDscreen: true },{ wheels: 5 },{ model: 6},{ weight: 500},{ mirrors: 4},];

but so the seria from 1st object is unchanged. The result should be

{ seria: 22 ,model: 6, wheels: 4, LCDscreen: true, weight: 500 , mirrors: 4};

Whats the best approach?

You can simple loop through the array and spread the array objects inside the mazda object. This is the fastest method after using a for loop.

 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)

I think this does what you want it to. Take each item in the newList and add it as a new property to the mazda object.

 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)

This can be done in a single line:

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

This iterates over all objects in the newItems list and merges them into mazda one after one.

If you don't want the mazda object to be modified but instead get a new object, use an empty object ( {} ) as first parameter to Object.assign :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM