How to create an object with dynamic keys in JavaScript

published: 05 Jun 2022

2 min read

How to create an object with dynamic keys in JavaScript

To create an object with dynamic keys in JavaScript, you can use ES6's computed property names feature.

The computed property names feature allows us to assign an expression as the property name to an object within object literal notation.

Here is an example:

const key = 'title';
const value = 'JavaScript';

const course = {
    [key]: value,
    price: '$99'
};

console.log(course.title);  // JavaScript
console.log(course.price);  // $99 

The value of the key can be any expression as long as it is wrapped in brackets []:

const key = 'title';
const value = 'JavaScript';

const course = {
    [key + '2']: value,
    price: '$99'
};

console.log(course.title2);  // JavaScript
console.log(course.price);  // $99 

How to create an object with dynamic keys in JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming