Q:

How to Add a Key/Value Pair to an Object in Javascript

0

How to Add a Key/Value Pair to an Object in Javascript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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:

// 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:

// 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.

// 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);

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Test For an Empty Object in JavaScript... >>
<< How to Display a JavaScript Object...