tags:

views:

199

answers:

3

I have code like this.

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

I want to know does there is a way then key will replace to that "anything".

like

var json = {  
    "anything": "key attribute"     
};
+2  A: 

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.

tvanfosson
A: 

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

but this sould do it:

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

Its a bit tricky, but hey, it works!

Here Be Wolves
A: 

This should do the trick:

var key = "anything";

var json = {};

json[key] = "key attribute";
D. Evans