How to Add a Key/Value Pair to an Object in Javascript
Topic: JavaScript / jQueryPrev|Next
Answer: Use Dot Notation or Square Bracket
You can simply use the dot notation (.
) to add a key/value pair or a property to a JavaScript object.
Let's try out the following example to understand how it basically works:
Example
Try this code »// Sample object
var myCar = {
make: "Ferrari",
model: "Portofino",
year: 2018
};
// Adding a new property
myCar.fuel = "Petrol";
console.log(myCar);
Alternatively, you can also use the square bracket notation ([]
) to add a key/value pair to a JavaScript object. The following example produces the same result as the previous example:
Example
Try this code »// Sample object
var myCar = {
make: "Ferrari",
model: "Portofino",
year: 2018
};
// Adding a key/value pair
myCar["fuel"] = "Petrol";
console.log(myCar);
The advantage of using square bracket notation is, you can substitute the key inside the square bracket with a variable to dynamically assign a key or property name to an object.
Example
Try this code »// Sample object
var myCar = {
make: "Ferrari",
model: "Portofino",
year: 2018
};
// Sample variables
var myKey = "fuel";
var myValue = "Petrol";
// Dynamically adding a key/value pair
myCar[myKey] = myValue;
console.log(myCar);
See the tutorial on JavaScript Objects to learn more about creating and manipulating objects.
Related FAQ
Here are some more FAQ related to this topic: