0
var color3 = {
    name: 'Black',
    type: 'special',
    rating: 1
};

var rateColor3 = (colorName, Nrating) => ({ ...colorName, Nrating });
console.log(color3.rating); ///// 1
console.log(rateColor3(color3, 6).rating);//////1
console.log(color3.rating);//////1

I want to use object spread operator while keeping color3 immutable, But the output of my 2nd console.log is 1 instead of 6, what am i doing wrong?

dwjohnston
  • 11,163
  • 32
  • 99
  • 194
Gavish Kumar
  • 59
  • 1
  • 9

4 Answers4

2

You are assigning a the value 6 to the key NRating to the object, not the existing rating.

So your object would look like this:

{
    name: 'Black',
    type: 'special',
    rating: 1,
    Nrating: 6
}

To override the existing rating property, you have to do:

var rateColor3 = (colorName, Nrating) => ({ ...colorName, rating: Nrating });

or change your parameter Nrating to rating.

var color3 = {
    name: 'Black',
    type: 'special',
    rating: 1
};

var rateColor3 = (colorName, rating) => ({ ...colorName, rating });

console.log(rateColor3(color3, 6));
JAM
  • 6,045
  • 1
  • 32
  • 48
  • _"You are applying a new property to your object called Nrating"_ - actually, that is not true. And still it doesn't answer the OP question. – kind user Dec 14 '18 at 19:55
  • @kinduser try `console.log(rateColor3(color3, 6).Nrating)` using the original code. – JAM Dec 14 '18 at 19:58
  • It's not _applying_ a new property. It's just a basic dot notation to _get_ specified key value. – kind user Dec 14 '18 at 19:59
  • 1
    Oh sorry for beeing semantically incorrect. I'll fix it shortly! – JAM Dec 14 '18 at 20:01
1

First of all you are not mutating the original color3 object, but returning a new one. Secondly:

({ ...colorName, Nrating });

will return a new object with a fourth prop Nrating: 6, since it's a shorthand for object assignment. You'll have to simply assign the value to the rating key instead.

var color3 = {
    name: 'Black',
    type: 'special',
    rating: 1
};

var rateColor3 = (colorName, Nrating) => ({ ...colorName, rating: Nrating });

console.log(rateColor3(color3, 6));
kind user
  • 40,029
  • 7
  • 67
  • 77
0

Nrating needs a property name

var color3 = {
   name: 'Black',
   type: 'special',
   rating: 1
};

var rateColor3 = (colorName, Nrating) => ({ ...colorName, rating: Nrating });
console.log(color3.rating); ///// 1
console.log(rateColor3(color3, 6).rating);//////6
console.log(color3.rating);//////1
varoons
  • 3,807
  • 1
  • 16
  • 20
0

You have created a new property Nrating. Change your rating to Nrating.

var color3 = {
    name: 'Black',
    type: 'special',
    rating: 1
};

var rateColor3 = (colorName, Nrating) => ({ ...colorName, Nrating });
console.log(color3.rating); ///// 1
console.log(rateColor3(color3, 6).Nrating);//////6
console.log(color3.rating);//////1
JMP
  • 4,417
  • 17
  • 30
  • 41