Saturday, September 21, 2024
Google search engine
HomeLanguagesJavascriptJavaScript How to add an element to a JSON object ?

JavaScript How to add an element to a JSON object ?

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"}

RELATED ARTICLES

Most Popular

Recent Comments