 
 Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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 create an object property from a variable value in JavaScript?
JS has 2 notations for creating object properties, the dot notation and bracket notation.
To create an object property from a variable, you need to use the bracket notation in the following way −
Example
const obj = {a: 'foo'}
const prop = 'bar'
// Set the property bar using the variable name prop
obj[prop] = 'baz'
console.log(obj);
Output
This will give the output −
{
   a: 'foo',
   bar: 'baz'
}
ES6 introduces computed property names, which allow you to do −
Example
const prop = 'bar'
const obj = {
   // Use a as key
   a: 'foo',
   // Use the value of prop as key
   [prop]: 'baz'
}
console.log(obj);
Output
This will give the output −
{
   a: 'foo',
   bar: 'baz'
}Advertisements
                    