Is there a way to use variable keys in a JavaScript object literal?
Solution 1:
In ES6, use computed property names.
const key = "anything";
const object = {
[key]: "key attribute"
// ^^^^^ COMPUTED PROPERTY NAME
};
Note the square brackets around key
. You can actually specify any expression in the square brackets, not just a variable.
Solution 2:
Yes. You can use:
var key = "anything";
var json = { };
json[key] = "key attribute";
Or simply use your second method if you have the values at hand when writing the program.