- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Advertisements