How to add a property to a JavaScript object using a variable as the name?


In this article, you will understand how to add a property to a JavaScript object using a variable as the name. Adding property to an object can be achieved by two methods. The first is the dot (.) notation and the second is using the brackets([]).

Example 1

In this example, let’s use the dot (.) notation.

var inputObject = {a: "value1"};
console.log("An object is created with properties: ", inputObject)

inputObject.b = "value2";

console.log("
After adding properties, the object now contains: ", inputObject) console.log(inputObject)

Explanation

  • Step 1 − Define an object namely inputObject.

  • Step 2 − Add an additional property to the object using dot notation.

  • Step 3 − Display the values.

Example 2

In this example,

var inputObject = {a: "value1"};
console.log("An object is created with properties: ", inputObject)

inputObject['c'] = "value3"

console.log("
After adding properties, the object now contains: ", inputObject) console.log(inputObject)

Explanation

  • Step 1 − Define an object namely inputObject.

  • Step 2 − Add an additional property to the object using bracket notation.

  • Step 3 − Display the values.

Updated on: 16-Feb-2023

187 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements