How to use a variable for a key in a JavaScript object literal?


In JavaScript, sometimes, we are required to use the variables as an object key. For example, when fetching data from the API and not sure about all the response data attributes, we must iterate through the response object and store every property of it.

However, we can’t use the variables as a key while creating the object, but after creating, we can add the variable properties to the object.

Syntax

Users can follow the syntax below to use a variable for a key in a JavaScript object.

object[key] = value;

In the above syntax, ‘key’ is a variable containing some value.

Example

In the example below, we have created the object containing the table properties. Also, we have created the ‘dimensions’ variable to store the table's dimensions. The ‘key’ variable contains the ‘dimensions’ as a string value.

After creating the object, we used the ‘key’ variable as an object property and the value of the ‘dimension’ variable as an object property value.

<html>
<body>
   <h2>Using variables as key of JavaScript object</h2>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById("content");
      let object = {
         "table_id": 1,
         "table_name": "table1",
         "table_price": 100
      };
      let dimesions = "100 x 100";
      let key = "dimensions";
      object[key] = dimesions;
      for (let key in object) {
         content.innerHTML += key + " : " + object[key] + "<br>";
      }
   </script>
</body>
</html>

In the output, users can observe that table dimensions are stored as a value of the ‘dimensions’ object.

Example

In the example below, we have created an empty object. After that, we have used the for loop to make 10 iterations. We use the ‘I’ in every iteration as a key and i*i as a property value.

In this way, we store the square of the number as a value and the number as a key itself.

<html>
<body>
   <h2>Using variables as key of JavaScript object</h2>
   <div id="content"> </div>
   <script>
      let content = document.getElementById("content");
      let object = {};
      for (let i = 0; i < 10; i++) {
         object[i] = i * i;
      }
      content.innerHTML = "The object is: " + JSON.stringify(object) + "<br>";
      for (let i = 0; i < 10; i++) {
         content.innerHTML += "The square of " + i + " is " + object[i] + "<br>";
      }
   </script>
</body>
</html>

Users learned to use the variable as a key while creating the JavaScript object. When we use the variable as a key, it actually uses the variable’s value as a key.

Updated on: 06-Apr-2023

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements