Is there a way to use variable keys in a JavaScript object literal?

Viewed 88996

I have code like this.

var key = "anything";   
var object = {   
    key: "key attribute"  
};

I want to know if there is a way to replace that key with "anything".

like

var object = {  
    "anything": "key attribute"     
};
8 Answers

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.

On modern Javascript (ECMAScript 6) you can sorround the variable with square brackets:

var key = "anything";

var json = {
    [key]: "key attribute"
};

This should do the trick:

var key = "anything";

var json = {};

json[key] = "key attribute";

Well, there isn't a "direct" way to do this...

but this should do it:

json[key] = json.key;
json.key = undefined;

Its a bit tricky, but hey, it works!

Related