Friday, October 10, 2025
HomeLanguagesJavascriptJavaScript Set object key by variable

JavaScript Set object key by variable

In order to set an object’s key by variable, here are few steps to follow. 

Steps:

  • First make a variable.
  • Then make a object.
  • Assign that variable a value.

Example-1: This example sets the object key by variable key and then inserts {“GFG_key”:”GFG_Val”} object to a array. 

html




<h1 style="color:green;">
    GeeksForGeeks
</h1>
<p id="GFG_UP" style="color:green;
            font-size: 20px;">
</p>
  
<button id="GFG_Button" onclick="set()">
    set
</button>
<p id="GFG_P" style="color:green;
            font-size: 20px;">
</p>
<script>
    myArray = [{
        'key_1': 'value_1'
    }, {
        'key_2': 'value_2'
    }];
    var up =
        document.getElementById("GFG_UP");
      
    up.innerHTML =
    JSON.stringify(myArray);
      
    var down =
        document.getElementById("GFG_P");
      
    function set() {
      
        var key = "GFG_key";
        var obj = {};
        obj[key] = "GFG_Val";
        myArray.push(obj);
        down.innerHTML = JSON.stringify(myArray);
    }
</script>


Output:

JavaScript Set object key by variable

JavaScript Set object key by variable

Example-2:This example sets the object key by variable key as well as object value by variable val and then inserts {“GFG_key”:”GFG_N_Val”} object to a array. 

html




<h1 style="color:green;">
    GeeksForGeeks
</h1>
<p id="GFG_UP" style="color:green;
            font-size: 20px;">
</p>
  
<button id="GFG_Button" onclick="set()">
    set
</button>
<p id="GFG_P" style="color:green;
            font-size: 20px;">
</p>
<script>
    myArray = [{
        'key_1': 'value_1'
    }, {
        'key_2': 'value_2'
    }];
    var up = document.getElementById("GFG_UP");
    up.innerHTML = JSON.stringify(myArray);
    var down = document.getElementById("GFG_P");
      
    function set() {
      
        var key = "GFG_key";
        var obj = {};
        var val = "GFG_N_Val";
        obj[key] = val;
        myArray.push(obj);
        down.innerHTML = JSON.stringify(myArray);
    }
</script>


Output:

JavaScript Set object key by variable

JavaScript Set object key by variable

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32348 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6715 POSTS0 COMMENTS
Nicole Veronica
11878 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11941 POSTS0 COMMENTS
Shaida Kate Naidoo
6837 POSTS0 COMMENTS
Ted Musemwa
7096 POSTS0 COMMENTS
Thapelo Manthata
6791 POSTS0 COMMENTS
Umr Jansen
6791 POSTS0 COMMENTS