Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using spread operator to update an object value

People also ask

How do you change the value of an object using the spread operator?

To use the spread operator to update an object value with JavaScript, we use the spread operator in a new object. const o2 = { ... o1, a: "updated a" }; console. log(o2);

How do you update an object in an array using the 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 Spread operator be used on object?

Spread syntax can be used when all elements from an object or array need to be included in a new array or object, or should be applied one-by-one in a function call's arguments list. There are three distinct places that accept the spread syntax: Function arguments list ( myFunction(a, ...


The properties are added in order, so if you want to override existing properties, you need to put them at the end instead of at the beginning:

return {
  value: {
    ...initialState,
    ...newObject
  }
}

You don't need newObject (unless you already have it lying around), though:

return {
  value: {
    ...initialState,
    isAvailable: newValue
  }
}

Example:

const o1 = {a: "original a", b: "original b"};
// Doesn't work:
const o2 = {a: "updated a", ...o1};
console.log(o2);
// Works:
const o3 = {...o1, a: "updated a"};
console.log(o3);

If you know the name of the property (a in the example below), then @crowder's answer is perfect:

const o3 = {...o1, a: "updated a"};
console.log(o3);

If the property name is in a variable, then you need to use Computed Property names syntax:

let variable = 'foo'
const o4 = {...o1, [variable]: "updated foo"};
console.log(o4);