0

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?

6
  • 3
    Can you show what you want the result to be? Commented Dec 9, 2020 at 12:49
  • do you want to change the existing values or append onto it? Commented Dec 9, 2020 at 12:52
  • const mazda = { seria: 22 ,model: 6, wheels: 4, LCDscreen: true, weight: 500 , mirrors: 4}; Commented Dec 9, 2020 at 12:52
  • I Want to add values from second object to the first one, without changing seria. Commented Dec 9, 2020 at 12:53
  • 1
    Why wheels: 4 is not updated with 5 in the output? Commented Dec 9, 2020 at 13:01

3 Answers 3

1

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)

Sign up to request clarification or add additional context in comments.

2 Comments

You are using spread syntax, not destructuring
Sorry my bad. Thanks for updating.
0

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)

Comments

0

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)

2 Comments

can you explaint what is the use of ... ?
@SandrinJoy Yes sure it is the spread syntax

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.