Wednesday, July 3, 2024
HomeLanguagesJavascriptHow to add key/value pair to a JavaScript object ?

How to add key/value pair to a JavaScript object ?

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

html




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


Output:

 

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

html




<h1 style="color:green;">
    neveropen
</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>


Output:

 

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments