How can I call the "keys" of an object programmatically in JavaScript?

What I want is what I do every day in Python. In JS, this does not work, most likely because I suck JS.

This is the Python code that will do what I want:

>key = 'just_a_key'
>value = 5
>dict = {key: value}
>dict
{'just_a_key':5}
>dict['just_a_key'}
5

This does not work in JS, the key will be the just named "key". I know this because I really don't create a dictionary here, but using json to create an object when I write the same code. So now my question is: how can I programmatically name objects "keys" (or properties?) In JS?

+3
source share
2 answers

Like this:

dict = {};

dict[key] = value;

JavaScript does not evaluate expressions for property names in its object notation, but does so if you use the square bracket form of an object member statement.

MDN

+13

: 2012 , ES2015/ES6 . (. ) :

const key = 'just_a_key';

const obj = { [key]: 5 };

- JavaScript, , (.. [key]). , key ( ) , .


/ ES6:

var obj = {},
    key = 'just_a_key';

obj[key] = 5;
+5

All Articles