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'
}

Updated on: 27-Nov-2019

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements