The problem

Suppose I have the following object literal:

var obj = {key1: value1, key2: value2};

How can I add {key3: value3} to object obj ?

Answer

There are two ways to add a new property to an object:

Use dot notation

If you know the key name of the property, the key3 in this example

obj.key3 = "value3";

Use square bracket notation

This form allow to give the key name dynamically.

obj["key3"] = "value3";

This form is widely used when the key name is dynamically determined. Like in this example:

var getProperty = function (propertyName) {
    return obj[propertyName];
};
 
getProperty("key1");
getProperty("key2");
getProperty("key3");

References & Resources

  • N/A