
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to set dynamic property keys to an object in JavaScript?
Previously it is a two-step process to create a property in an object but the advent of ES6 has made the task very simple. In only one step we can create a property dynamically. Let's discuss it in a nutshell.
Old method(2 step process)
Example
In the following example, the property, instead of declaring in the object itself, is declared outside the object, making it a two-step process.
<html> <body> <script> let person = 'name'; let student = { // step-1 id: 1, }; student[person] = 'nani'; // step-2 document.write(JSON.stringify(student)); </script> </body> </html>
Output
{"id":1,"name":"nani"}
ES6 Method
Example
In the following example, the property of the object is declared directly in the object itself rather than declaring it outside the object, making it a 1 step process
<html> <body> <script> let person = 'name'; let student = { id: 1, [person] : "nani" }; document.write(JSON.stringify(student)); </script> </body> </html>
Output
{"id":1,"name":"nani"}
- Related Questions & Answers
- JavaScript: replacing object keys with an array
- How to delete a property of an object in JavaScript?
- How to get Property Descriptors of an Object in JavaScript?
- How to convert square bracket object keys into nested object in JavaScript?
- How to Declare an Object with Computed Property Name in JavaScript?
- JavaScript map value to keys (reverse object mapping)
- Dynamic programming to check dynamic behavior of an array in JavaScript
- How to create an object property from a variable value in JavaScript?
- Convert set to object - JavaScript?
- How to set JavaScript object values dynamically?
- PHP print keys from an object?
- Recursively list nested object keys JavaScript
- Fetching object keys using recursion in JavaScript
- How to allocate memory to an object whose length is set to 0 - JavaScript?
- How to clone an object in JavaScript?
Advertisements