DEV Community

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

Posted on

3

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)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more