JavaScript - Set object key by variable


To set object key by variable, the code is as follows −

Example

 Live Demo

<!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 property name and value and clicking on the ‘CLICK HERE’ button −

Updated on: 12-May-2020

184 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements