Home > Web Front-end > JS Tutorial > body text

How to add elements to a JSON object using JavaScript?

WBOY
Release: 2023-09-09 19:01:10
forward
1224 people have browsed it

如何使用 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);
Copy after login
  • 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);
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!