Here is my object literal:
var obj = {key1: value1, key2: value2};
How can I add {key3: value3}
to the object?
Here is my object literal:
var obj = {key1: value1, key2: value2};
How can I add {key3: value3}
to the object?
You could use either of these (provided key3 is the acutal key you want to use)
arr[ 'key3' ] = value3;
or
arr.key3 = value3;
If key3 is a variable, then you should do:
var key3 = 'a_key';
arr[ key3 ] = value3;
In this case, arr.key3=value3
would not work like you expect.
That's not an array. It is an object constructed using object literal notation and there are two ways to add new properties to such an object:
var obj = {
key1: value1,
key2: value2
};
obj.key3 = "value3";
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:
var arr = [];
var arr = new Array();
arr.key3 = value3;
because your arr is not really an array... It's a prototype object. The real array would be:
var arr = [{key1: value1}, {key2: value2}];
but it's still not right. It should actually be:
var arr = [{key: key1, value: value1}, {key: key2, value: value2}];
Your example shows an Object, not an Array. In that case, the preferred way to add a field to an Object is to just assign to it, like so:
arr.key3 = value3;
You can either add it this way:
arr['key3'] = value3;
or this way:
arr.key3 = value3;
The answers suggesting keying into the object with the variable key3
would only work if the value of key3
was 'key3'
.