Here is my object literal:
var obj = {key1: value1, key2: value2};
How can I add field key3
with value3
to the ob
And we want to add prop2 : 2
to this object, these are the most convenient options:
object.prop2 = 2;
object['prop2'] = 2;
So which one do we use then?
The dot operator is more clean syntax and should be used as a default (imo). However, the dot operator is not capable of adding dynamic keys to an object, which can be very useful in some cases. Here is an example:
const obj = {
prop1: 1
}
const key = Math.random() > 0.5 ? 'key1' : 'key2';
obj[key] = 'this value has a dynamic key';
console.log(obj);
When we want to merge the properties of 2 objects these are the most convenient options:
Object.assign()
, takes a target object as an argument, and one or more source objects and will merge them together. For example:const object1 = {
a: 1,
b: 2,
};
const object2 = Object.assign({
c: 3,
d: 4
}, object1);
console.log(object2);
...
const obj = {
prop1: 1,
prop2: 2
}
const newObj = {
...obj,
prop3: 3,
prop4: 4
}
console.log(newObj);
Which one do we use?
Object.assign()
is more dynamic because we have access to all objects which are passed in as arguments and can manipulate them before they get assigned to the new Object.