JavaScript - Set object key by variable

JavascriptWeb DevelopmentObject Oriented Programming

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


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   .sample {
      font-size: 18px;
      font-weight: 500;
      color: red;
<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>
Click on the above button to set property name and value to above text
fields respectively
   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];


On entering property name and value and clicking on the ‘CLICK HERE’ button −

Published on 12-May-2020 05:46:16