1
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
};
3960278
  • 756
  • 4
  • 12
  • 1
    [`...` is not an operator!](https://stackoverflow.com/questions/37151966/what-is-spreadelement-in-ecmascript-documentation-is-it-the-same-as-spread-oper/37152508#37152508) – Felix Kling Jul 19 '19 at 06:47
  • 1
    Since "object spread" can only be used inside an object literal you are always going to be creating a new object. – Felix Kling Jul 19 '19 at 06:47
  • @FelixKling accepted, its not an operator, my bad – 3960278 Jul 19 '19 at 07:25

3 Answers3

2

Assign the spread right side to object1

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

object1 = { ...object1,b: 5};
console.log(object1);
ellipsis
  • 12,049
  • 2
  • 17
  • 33
  • pretty much like object1 = object2, which changes the reference of object1, i know this, but i am wondering without changing the reference – 3960278 Jul 19 '19 at 06:32
  • 2
    @SuryapratapSingh Since this is the trivial and obvious solution, can you clarify why you don't like it? Or what your actual goal is here? –  Jul 19 '19 at 06:37
  • @SuryapratapSingh goal of spread operator is to change the reference of object could you please let us know what are purpose for this. – Amit kumar Jul 19 '19 at 06:41
  • The goal is just to edit a bigger object with some properties as Object.assign with first parameter as object to edit. In some scenarios, may be let's say where view will update based on the object's some properties, or some kind of an event for change of the object reference, will trigger even when we don't want. – 3960278 Jul 19 '19 at 06:50
2

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.

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
0

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} 
Akxe
  • 9,694
  • 3
  • 36
  • 71