How to create an object property from a variable value in JavaScript?

JavascriptFront End TechnologyObject Oriented Programming

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'
}
raja
Published on 27-Nov-2019 16:49:49
Advertisements