Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update Array containing objects using spread operator

I have an array containing objects in javascript / typescript.

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

How can I update name of the second element (with id 2) and copy the array to a new array using javascript spread (...) operator?

like image 846
developer Avatar asked Jun 13 '17 14:06

developer


People also ask

How do you update an array in an object's spread operator?

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.

Can you spread an array of objects?

For typical arrays, all indices are enumerable own properties, so arrays can be spread into objects.

How do you update an item in an array?

To update an object's property in an array of objects, use the map() method to iterate over the array. On each iteration, check if the current object is the one to be updated. If it is, modify the object and return the result, otherwise return the object as is. Copied!


1 Answers

You can use a mix of .map and the ... spread operator

You can set the value after you've created your new array

let array = [{id:1,name:'One'}, {id:2, name:'Two'}, {id:3, name: 'Three'}];    let array2 = array.map(a => {return {...a}})    array2.find(a => a.id == 2).name = "Not Two";    console.log(array);  console.log(array2);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Or you can 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);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 124
George Avatar answered Sep 26 '22 03:09

George