How to JSON Add an Element in Javascript?

Nov 02, 2022 . Admin



Hello friends,

In this example, you will learn how to JSON add an element in javascript. it's a simple example of adding a new array element to a JSON object. I explained simply how to add an element to a JSON object with javascript. This article goes in detailed on how to add key-value pair in the JSON object.

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. This example adds {“prop_4”: “val_4”} to the GFG_p object by using dot notation.

So, let's see bellow solution:

Example
index.html
<!DOCTYPE html>
<html>
  
<head>
    <title>
        How to JSON Add an Element in Javascript?
    </title>
</head>
  
<body style="text-align:center;">
  
    <h1 style="color:#006AFF;">  
           How to JSON Add an Element in Javascript?
        </h1>
  
    <p id="GFG_up"
       style=" font-weight: bold">
    </p>
  
    <button onclick="java()">
        Click to add
    </button>
  
    <p id="GFG_down" 
       style="color:#006AFF;
              font-weight: bold" ;>
    </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 java() {
            GFG_p.prop_4 = "val_4";
            p_down.innerHTML = JSON.stringify(GFG_p);
        }
    </script>
</body>
  
</html>
Output:

I hope it will help you...

#Javascript