How can I add a key/value pair to a JavaScript object?
There are two ways to add new properties to an object:
var obj = {
key1: value1,
key2: value2
};
Using dot notation:
obj.key3 = "value3";
Using square bracket notation:
obj["key3"] = "value3";
The first form is used when you know the name of the property. The second form is used when the name of the property is dynamically determined. Like in this example:
var getProperty = function (propertyName) {
return obj[propertyName];
};
getProperty("key1");
getProperty("key2");
getProperty("key3");
A real JavaScript array can be constructed using either:
The Array literal notation:
var arr = [];
The Array constructor notation:
var arr = new Array();
Year 2017 answer: 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.
Live example
var obj = {key1: "value1", key2: "value2"};
Object.assign(obj, {key3: "value3"});
document.body.innerHTML = JSON.stringify(obj);
Year 2018 answer: object spread operator {...}
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.
Live example
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);
Year 2019 answer
Object assignment operator +=
:
obj += {key3: "value3"};
Oops... I got carried away. Smuggling information from the future is illegal. Duly obscured!