Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 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