DEV Community

Muhammad Bilal Mohib-ul-Nabi
Muhammad Bilal Mohib-ul-Nabi

Posted on

How to create an object with dynamic keys in JavaScript?

To create object with dynamic key the format is

const key = "This is key"
const tempObj = {
  [key]:60,
  price:'99'
}
console.log(tempObj.key) //Output = 60
Enter fullscreen mode Exit fullscreen mode

Here is another example:

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

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

console.log(course.title); // JavaScript
console.log(course.price); // $99
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode

In this way you can create object with dynamic keys in javascript.
Thank you for reading.

Top comments (0)