Open In App
Related Articles

JavaScript How to add an element to a JSON object ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

In this article, we will learn how to add an element to the JSON object using JavaScript. In order to add Key/value pair to a JSON object, Either we use dot notation or square bracket notation. Both methods are widely accepted.

Example 1: This example adds {“prop_4”: “val_4”} to the GFG object by using dot notation

Javascript

let GFG = {
    prop_1: "val_1",
    prop_2: "val_2",
    prop_3: "val_3"
};
 
GFG.prop_4 = "val_4";
 
console.log(JSON.stringify(GFG));

                    

Output
{"prop_1":"val_1","prop_2":"val_2","prop_3":"val_3","prop_4":"val_4"}

Example 2: This example adds {“prop_4”: “val_4”} to the GFG object by using square bracket notation

Javascript

let GFG = {
    prop_1: "val_1",
    prop_2: "val_2",
    prop_3: "val_3"
};
 
GFG["prop_4"] = "val_4";
 
console.log(JSON.stringify(GFG));

                    

Output
{"prop_1":"val_1","prop_2":"val_2","prop_3":"val_3","prop_4":"val_4"}

Last Updated : 20 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads