Reputation: 1063
My code involves adding properties to an object based on some test cases. Here are the two ways i which I did it. I am using this object for inline styling in reactjs.
var myObject = {}
//some code
myObject = {
key1: value1,
key2:value
}
//some code
myObject = {
key3: value3,
key4: value4
}
All the properties(styles) were not applied consistently. So I tried doing this instead and it worked properly. Please explain why this is happening.
var myObject = {}
//some code
myObject = {
key1: value1,
key2:value
}
//some code
myObject.key3 = value3;
myObject.key4 = value4;
What is the difference between these two ways?
Upvotes: 0
Views: 81
Reputation: 173
Consider using Object.assign in first case, cause otherwise myObject
would contain only key3
and key4
.
var myObject = {}
//some code
myObject = {
key1: value1,
key2:value
}
//some code
Object.assign(myObject,{
key3: value3,
key4: value4
})
Upvotes: 1
Reputation: 26
There is difference between the two cases
the first case:
myObject = { key1: value1, key2:value }
means creating a new object and assigning it to variable myObject
While in the second case:
myObject.key3 = value3;
myObject.key4 = value4;
mean adding new property/value to the existing object.
Upvotes: 0
Reputation: 431
In the first snippet you are not adding properties to an object, you are overwriting the whole myObject
. In the second snippet you are assigning a single value to a key instead, ie. adding properties with values.
For example:
var i = {num: 1};
i.num = 2;
console.log(i.num); // 2
i = {str: "Hello"};
console.log(i.num); // undefined
console.log(i.str); // "Hello"
i.num = 1;
console.log(i.num); // 1
console.log(i.str); // "Hello"
Upvotes: 1