0
votes

I just have a brief question about using spread operators on objects, when we are trying to return a copy of the object with a field changed. I've been working through a PluralSight tutorial having a lot to do with React and Redux, and I've run into this usage of the spread operator:

let original = {name: 'Joel', favoriteFood: 'oranges', age: 26};
let happyBirthday = {...original, age: 27};

Obviously this isn't the exact code from the example, but that is the usage I'm a little confused by. My initial understanding would be that this would result in an object with two age keys, which obviously doesn't work. Does this work by just overwriting the value of the key that's duplicated? Could I say:

let obj = {a: 2, a: 'no actually 3', a: 'nevermind...', a: 2};

And then have obj.a be 2? This is a very small clarification that I'm looking for but I was thrown off when I saw this for some reason! Thanks!

2
Yes, it overwrites the key. You don't want copies of the same key.jmargolisvt
Open your browser console and type var x = {a:1, b:2, c:3, c:4}; x; and see what it outputs. Some times the easiest way to determine behaviour is just to try things.Taplar
same key will be replaced by the latter one. if you do this, let obj = {a: 2, a: 'no actually 3', a: 'nevermind...', a: 3};. obj.a will be 3tcf01
It will overwrite them in order listed in code. This is a common trick to provide a default object, the spread it into a new one combined with passed parameters.Trevor

2 Answers

2
votes

Objects cannot have duplicate keys. If you assign a key to an object when that object already has said key, or write an object initializer with duplicate keys, the prior value at that key will be overwritten:

const obj = {
  foo: 'foo',
  bar: 'bar',
};

obj.foo = 'new';
console.log(obj);

const obj = {
  foo: 'foo',
  bar: 'bar',
  foo: 'new',
};

console.log(obj);

When using object spread, the same sort of thing is going on. If you add a key-value pair when a prior key already exists in the object initializer (by spread or otherwise), the prior value will be overwritten.

let happyBirthday = {...original, age: 27};

is very similar to

// Create a new object with all properties of `original`:
let happyBirthday = Object.assign({}, original);
// Assign to the `age` property of the new object:
happyBirthday.age = 27;
1
votes
let original = {name: 'Joel', favoriteFood: 'oranges', age: 26};
let happyBirthday = {...original, age: 27};

happyBirthday will be an object that is identical to original but with the age overwritten.

So that would result in an object like this:

{name: 'Joel', favoriteFood: 'oranges', age: 27} // Notice the age