Update object in array JavaScript using the spread operator | Example

  • by

use both method map and the spread operator to update objects in array JavaScript. set the value after you’ve created your new array.

Update object in array JavaScript using the spread operator

Simple example code update name of the second element (with id 2) and copy the array to a new array using JavaScript spread (…) operator

<!DOCTYPE html>
<html>
<body>

  <script>
    let array = [{id:1,name:'One'}, {id:2, name:'Two'}, {id:3, name: 'Three'}];

    let res = array.map(a => {return {...a}})

    res.find(a => a.id == 2).name = "Not Two";

    console.log(res);
  </script>

</body>
</html> 

Output:

Update object in array JavaScript using the spread operator

Or do it in the .map

let array = [{id:1,name:'One'}, {id:2, name:'Two'}, {id:3, name: 'Three'}];

let array2 = array.map(a => {
  var returnValue = {...a};

  if (a.id == 2) {
    returnValue.name = "Not Two";
  }

  return returnValue
})


console.log(array);
console.log(array2);

or with Object.assign :

let new_array = array.map(element => element.id == 2 ? Object.assign({}, element, {name : 'New Name'}) : element);

Do comment if you have any doubts or suggestions on this JS object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.