简体   繁体   中英

Is it possible to update an object using spread operator, not creating new one?

var object1 = {
  a: 1,
  b: 3
};

Object.assing(object1, {b: 5});

This will make:

object1 = {
  a: 1,
  b: 5
}

The question is can this be achieved by spread operator ... Which will return new Object instead of updating object1

var object2 = {...object1, b: 5}

Same as:

var object2 = Object.assign{{}, object1, {b: 5}}

Here

object2 = {
  a: 1,
  b: 5
}

but

object1 {
  a: 1,
  b: 3
};

Assign the spread right side to object1

 var object1 = { a: 1, b: 3 }; object1 = { ...object1,b: 5}; console.log(object1);

When you do {...object1, b: 5} you're creating a new object using object literal notation , which is used to initialize a new object in memory.

So, when you do:

var object2 = {...object1, b: 5}

It's more or less the same as doing:

var object2 = {a: 1, b: 3, b: 5} // -> {a: 1, b: 5} -> creating a new object

So, the thing which is creating the new object here isn't the spread syntax ( ... ), but rather the object literal ( {} ).

Thus, unless you're willing to reassign object1 to the new object reference, you won't be able to modify object1 in-place solely using the spread syntax.

Using the spread operator requires you to create a new object. Object.assign however, takes as first parameter the object to edit. It is usually used with an empty object, but you can use it as follow.

 const object1 = { b: 5 } Object.assign(object1, { a: 1 }) console.log(object1) // { b:5, a: 1}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM