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
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
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 
In this way you can create object with dynamic keys in javascript.
Thank you for reading.
    
Top comments (0)