Skip to content
Related Articles
Open in App
Not now

Related Articles

JavaScript How to add an element to a JSON object ?

Improve Article
Save Article
  • Last Updated : 16 Jan, 2023
Improve Article
Save Article

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_p object by using dot notation

html




<h1 style="color:green;">
    GeeksforGeeks
</h1>
  
<p id="GFG_up"> </p>
  
<button onclick="Geeks()">
    Click to add
</button>
  
<p id="GFG_down"> </p>
  
<script>
    var GFG_p = {
        prop_1: "val_1",
        prop_2: "val_2",
        prop_3: "val_3"
    };
    var p_up =
        document.getElementById("GFG_up");
    var p_down =
        document.getElementById("GFG_down");
    p_up.innerHTML =
    JSON.stringify(GFG_p);
      
    function Geeks() {
        GFG_p.prop_4 = "val_4";
        p_down.innerHTML = JSON.stringify(GFG_p);
    }
</script>

Output:

JavaScript | How to add an element to a JSON object?

JavaScript | How to add an element to a JSON object?

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

html




<h1 style="color:green;">
    GeeksforGeeks
</h1>
  
<p id="GFG_up">
</p>
  
<button onclick="Geeks()">
    Click to add
</button>
  
<p id="GFG_down">
</p>
  
<script>
    var GFG_p = {
        prop_1: "val_1",
        prop_2: "val_2",
        prop_3: "val_3"
    };
    var p_up =
        document.getElementById("GFG_up");
    var p_down =
        document.getElementById("GFG_down");
    p_up.innerHTML =
    JSON.stringify(GFG_p);
      
    function Geeks() {
        GFG_p["prop_4"] = "val_4";
        p_down.innerHTML = JSON.stringify(GFG_p);
    }
</script>

Output:

JavaScript | How to add an element to a JSON object?

JavaScript | How to add an element to a JSON object?


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!