Here is my object literal:
var obj = {key1: value1, key2: value2};
How can I add field key3
with value3
to the ob
Two most used ways already mentioned in most answers
obj.key3 = "value3";
obj["key3"] = "value3";
One more way to define a property is using Object.defineProperty()
Object.defineProperty(obj, 'key3', {
value: "value3", // undefined by default
enumerable: true, // false by default
configurable: true, // false by default
writable: true // false by default
});
This method is useful when you want to have more control while defining property. Property defined can be set as enumerable, configurable and writable by user.