Here is my object literal:
var obj = {key1: value1, key2: value2};
How can I add field key3
with value3
to the ob
Object.assign()
Object.assign(dest, src1, src2, ...) merges objects.
It overwrites dest
with properties and values of (however many) source objects, then returns dest
.
The
Object.assign()
method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
var obj = {key1: "value1", key2: "value2"};
Object.assign(obj, {key3: "value3"});
document.body.innerHTML = JSON.stringify(obj);
{...}
obj = {...obj, ...pair};
From MDN:
It copies own enumerable properties from a provided object onto a new object.
Shallow-cloning (excluding prototype) or merging of objects is now possible using a shorter syntax than Object.assign().
Note that Object.assign() triggers setters whereas spread syntax doesn’t.
It works in current Chrome and current Firefox. They say it doesn’t work in current Edge.
var obj = {key1: "value1", key2: "value2"};
var pair = {key3: "value3"};
obj = {...obj, ...pair};
document.body.innerHTML = JSON.stringify(obj);
Object assignment operator +=
:
obj += {key3: "value3"};
Oops... I got carried away. Smuggling information from the future is illegal. Duly obscured!