Reputation: 59
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?
Upvotes: 0
Views: 376
Reputation: 41893
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));
Upvotes: 1
Reputation: 6205
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));
Upvotes: 2
Reputation: 4467
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
Upvotes: 0
Reputation: 3887
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
Upvotes: 0