The Wayback Machine - https://web.archive.org/web/20210613214320/https://www.geeksforgeeks.org/how-to-add-key-value-pair-to-a-javascript-object/
Skip to content
Related Articles

Related Articles

Improve Article
How to add key/value pair to a JavaScript object?
  • Last Updated : 22 Apr, 2019

In order to add key/value pair to a JavaScript object, Either we use dot notation or square bracket notation. Both methods are widely accepted.

Example 1: This example adds {“nextFavColor” : “red”} to the GFG_p object by using dot notation.




<!DOCTYPE html> 
<html> 
  
<head> 
    <title> 
        JavaScript | Add a key/value
        pair to JavaScript object 
    </title> 
</head> 
      
<body style = "text-align:center;"> 
    <h1 style = "color:green;" > 
        GeeksForGeeks 
    </h1> 
          
    <p id="GFG_up" style="color:red;"></p>
          
    <button onclick = "Geeks()"> 
        Click to add 
    </button> 
          
    <p id="GFG_down" style="color:green;"></p>
          
    <script> 
        var GFG_p = {fName:"Geeks", lName:"forGeeks",
                    age:100, favColor:"green"};
        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.nextFavColor = "Red";
            p_down.innerHTML = JSON.stringify(GFG_p);     
        } 
    </script> 
</body> 
  
</html>                    

Output:

  • Before clicking on the button:
  • After clicking on the button:

Example 2: This example adds {“thirdFavColor” : “blue”} to the GFG_p object by using square bracket notation.




<!DOCTYPE html> 
<html> 
  
<head> 
    <title> 
        JavaScript | Add a key/value
        pair to JavaScript object 
    </title> 
</head> 
      
<body style = "text-align:center;"> 
    <h1 style = "color:green;" > 
        GeeksForGeeks 
    </h1> 
          
    <p id="GFG_up" style="color:blue;"></p>
          
    <button onclick = "Geeks()"> 
        Click to add 
    </button> 
          
    <p id="GFG_down" style="color:green;"></p>
          
    <script> 
        var GFG_p = {fName:"Geeks", lName:"forGeeks", 
                    age:100, favColor:"green"};
        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["thirdFavColor"] = "blue";
            p_down.innerHTML = JSON.stringify(GFG_p);     
        } 
    </script> 
</body> 
  
</html>                    

Output:

  • Before clicking on the button:
  • After clicking on the button:



My Personal Notes arrow_drop_up
Recommended Articles
Page :