Set Object Key by Variable in JavaScript



In this article, we will learn to set the object keys by variable in JavaScript. Objects are dynamic collections of properties. We can use variables to add or change properties rather than using static keys. This is specifically helpful when handling dynamic data, like user input.

Dynamic Key Assignment

In JavaScript, object properties can be retrieved and assigned using bracket notation ([ ]). It enables the use of a string or variable as the key, so dynamic assignment of object properties is possible.

Syntax

object[variable] = value;

Here, the object is the target object, the variable is the variable containing the key name, and the value is the value to be assigned to that key.

Setting Object Keys from User Input

We create a simple web page that allows users to input a property name and value, and then dynamically sets that property on an object.

Following are the steps to set object keys from user input using HTML and JavaScript ?

  • When the user enters a property name and value in the input fields and clicks the button, the JavaScript code dynamically sets the key in the testObj object.
  • The bracket notation testObj[propertyKey.value] permits us to employ the value of propertyKey.value as the key within the object.
  • The object is then rendered on the page, with the new key-value pair.

Select the necessary DOM elements using querySelector and querySelectorAll ?

let sampleEle = document.querySelector(".sample");
let propertyKey = document.querySelector(".pName");
let propertyValue = document.querySelectorAll(".pName")[1];

An event listener is added to the button that triggers when clicked ?

document.querySelector(".Btn").addEventListener("click", () => {}

The key is taken from propertyKey.value, and the value from propertyValue.value ?

testObj[propertyKey.value] = propertyValue.value;

Example

Below is an example to set the object keys by variable in JavaScript ?

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .sample {
      font-size: 18px;
      font-weight: 500;
      color: red;
   }
</style>
</head>
<body>
<h1>Set object key by variable Example</h1>
Enter property name<input class="pName" type="text" /><br />
Enter property value<input class="pName" type="text" />
<br />
<div class="sample"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to set property name and value to above text
fields respectively
</h3>
<script>
   let sampleEle = document.querySelector(".sample");
   let propertyKey = document.querySelector(".pName");
   let propertyValue = document.querySelectorAll(".pName")[1];
   let testObj = {
      a: "Hello",
   };
   document.querySelector(".Btn").addEventListener("click", () => {
      testObj[propertyKey.value] = propertyValue.value;
      sampleEle.innerHTML ="testObj[" + propertyKey.value + "] = "+testObj[propertyKey.value];
   });
</script>
</body>
</html>

Output

On entering the property name and value and clicking on the ?CLICK HERE' button ?

Conclusion

Setting object keys dynamically with variables in JavaScript is a robust method that provides more flexibility when dealing with data. With bracket notation, it's simple to set or modify object keys dynamically based on values at runtime, like user input or API data. This technique is critical for developing dynamic and interactive web applications.

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-03-06T19:21:37+05:30

287 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements