Home >Web Front-end >JS Tutorial >How to add elements to a JSON object using JavaScript?
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 {}.
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.
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);
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!