How to add an element to a JSON object using JavaScript?


In this article, you will understand how to add an element to a JSON object using JavaScript.

JSON object literals are keys and values are separated by a colon surrounded by curly braces {}.

Example 1

In this example, we add an element to a json object using bracket notation,

var jsonObject = {
   members: 
   {
      host: "hostName",
      viewers: 
      {
         userName1: "userData1",
         userName2: "userData2"
      }
   }
}
console.log("A json object is defined as: ")
console.log(jsonObject);

console.log("
Adding an element using the bracket notation") jsonObject.members.viewers['userName3'] = 'userData3'; console.log("
A json object after adding a property is: ") console.log(jsonObject);
  • Step 1 − Define a json object namely ‘jsonObject’

  • Step 2 − Define the path to which the new element has to be added.

  • Step 3 − Add the new element to the defined path using bracket notation.

  • Step 4 − Display the result.

Example 2

In this example, push an array of elements

var jsonObject = {
   members: 
   {
      host: "hostName",
      viewers: 
      {
         userName1: "userData1",
         userName2: "userData2"
      }
   }
}
console.log("A json object is defined as: ")
console.log(jsonObject);

console.log("
Adding an element using the dot notation") jsonObject.members.viewers.userName3 = 'userData3'; console.log("
A json object after adding a property is: ") console.log(jsonObject);

Explanation

  • Step 1 − Define a json object namely ‘jsonObject’

  • Step 2 − Define the path to which the new element has to be added.

  • Step 3 − Add the new element to the defined path using dot notation.

  • Step 4 − Display the result.

Updated on: 16-Feb-2023

23K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements