How can I add a key/value pair to a JavaScript object?
Solution 1:
Solution 2:
There are two ways to add new properties to an object:
Using dot notation:
Using square bracket notation:
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:
A real JavaScript array can be constructed using either:
The Array literal notation:
The Array constructor notation:
Solution 3:
we could use either of these (provided key3 is the acutal key you want to use)
or
If key3 is a variable, then we should do:
Solution 4:
(Lodash only)
The second object will overwrite or add to the base object. undefined values are not copied.
_.extend / _.assign
The second object will overwrite or add to the base object. undefined will be copied.
_.defaults
The second object contains defaults that will be added to base object if they don't exist. undefinedvalues will be copied if key already exists.
$.extend
In addition, it may be worthwhile mentioning jQuery.extend, it functions similar to _.merge and may be a better option if you already are using jQuery.
The second object will overwrite or add to the base object. undefined values are not copied.
Object.assign()
It may be worth mentioning the ES6/ ES2015 Object.assign, it functions similar to _.merge and may be the best option if you already are using an ES6/ES2015 polyfill like Babel if you want to polyfill yourself.
The second object will overwrite or add to the base object. undefined will be copied.