snippetjavascriptCriticalCanonical
How can I add a key/value pair to a JavaScript object?
Viewed 0 times
pairkeyobjecthowaddcanvaluejavascript
Problem
Here is my object literal:
How can I add field
var obj = {key1: value1, key2: value2};How can I add field
key3 with value3 to the object?Solution
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:
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();Code Snippets
var obj = {
key1: value1,
key2: value2
};obj.key3 = "value3";obj["key3"] = "value3";var getProperty = function (propertyName) {
return obj[propertyName];
};
getProperty("key1");
getProperty("key2");
getProperty("key3");var arr = [];Context
Stack Overflow Q#1168807, score: 3049
Revisions (0)
No revisions yet.