Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a key/value pair to a JavaScript object?

Here is my object literal:

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

How can I add field key3 with value3 to the object?

like image 979
James Skidmore Avatar asked Jul 22 '09 23:07

James Skidmore


People also ask

How do you conditionally add key-value to an object?

To conditionally add a property to an object, we can make use of the && operator. In the example above, in the first property definition on obj , the first expression ( trueCondition ) is true/truthy, so the second expression is returned, and then spread into the object.


1 Answers

There are two ways to add new properties to an object:

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(); 
like image 179
Ionuț G. Stan Avatar answered Sep 30 '22 22:09

Ionuț G. Stan