developer developer -4 years ago 77
Javascript Question

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?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download