Home >Web Front-end >JS Tutorial >How to add elements to a JSON object using JavaScript?

How to add elements to a JSON object using JavaScript?

WBOY
WBOYforward
2023-09-09 19:01:101421browse

如何使用 JavaScript 将元素添加到 JSON 对象?

In this article, you will learn how to add elements to a JSON object using JavaScript.

JSON object literals are keys and values ​​separated by colons surrounded by braces {}.

Example 1

In this example, we use bracket notation to add elements to the json object,

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, that is, "jsonObject"

  • Step 2 - Define the path to which the new element must be added.

  • Step 3 - Use bracket notation to add new elements to the defined path.

  • Step 4 - Display the results.

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

illustrate

  • Step 1 - Define a json object, that is, "jsonObject"

  • Step 2 - Define the path to which the new element must be added.

  • Step 3 - Add new elements to the defined path using dot notation.

  • Step 4 - Display the results.

The above is the detailed content of How to add elements to a JSON object using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete