9

How to create an object with dynamic keys in JavaScript?

 2 years ago
source link: https://dev.to/bilalmohib/how-to-create-an-object-with-dynamic-keys-in-javascript-2k35
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

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

Copied From
https://attacomsian.com/blog/javascript-create-object-with-dynamic-keys#


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK