Igor Simic
1 year ago

How to change value of object inside an array using JavaScript


How to change object value inside of array of objects? Just loop over it and set new value? Wrong! 
Here is how!

So, let's say we have array of objects like this:

let data = [
  {
    foo:1,
    bar:2
  },
  {
    test:1,
    testis:2
  }

];
and now we want to change the value of test in second array element to have value 0.
To achieve this we will use spread operator ...  A.K.A. 3 dots. Spread operator will "spread" on the existing object and allow you to change the value of one or more object properties.
Let's do this. First we will select our second object element in array and then we will use spread operator and assign new value for "test"
data[1] = {...data[1],test:0}
By using same logic we can change multiple properties values:
data[1] = {...data[1], test:0, testis:0};

Baam! 

If you did not know,
now you know!