- 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
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' }
- Related Articles
- JavaScript: How to Create an Object from Key-Value Pairs
- How to access an object value using variable key in JavaScript?
- How to remove a property from a JavaScript object?
- How to delete a property of an object in JavaScript?
- How do we remove a property from a JavaScript object? - JavaScript
- How to create Date object from String value in Java?
- How to create an object with prototype in JavaScript?
- Sorting an array object by property having falsy value - JavaScript
- How to get Property Descriptors of an Object in JavaScript?
- How to create an object from class in Java?
- How do I remove a property from a JavaScript object?
- Removing property from a JSON object in JavaScript
- How to set dynamic property keys to an object in JavaScript?
- How to create JavaScript Date object from date string?
- How to create a JSON object in JavaScript? Explain with an example.

Advertisements