- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JavaScript - Set object key by variable
To set object key by variable, the code is as follows −
Example
<!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 −
- Related Articles
- How to access an object value using variable key in JavaScript?
- Javascript search for an object key in a set
- How to set a String as a key for an object - JavaScript?
- How to Sort object of objects by its key value JavaScript
- How to merge two object arrays of different size by key in JavaScript
- Call a JavaScript class object with variable?
- How to automate this object using JavaScript to set one key on each iteration as null?
- Test for existence of nested JavaScript object key in JavaScript
- Convert set to object - JavaScript?
- Count by unique key in JavaScript
- Extract key value from a nested object in JavaScript?
- JavaScript - Sort key value pair object based on value?
- Checking if a key exists in a JavaScript object
- Set JavaScript object values to null?
- How to sort an object in ascending order by the value of a key in JavaScript?

Advertisements