152

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"     
};

7 Answers 7

338

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.

1
  • 2
    That's fine for ES6 but what about older versions (IE11 will crash on the code above)
    – pascalzon
    Oct 29, 2018 at 7:17
128

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.

0
32

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

var key = "anything";

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

This should do the trick:

var key = "anything";

var json = {};

json[key] = "key attribute";
1
  • But he wants to do this in the context of an object literal.
    – user663031
    Apr 17, 2017 at 17:15
-2

Recently needed a solution how to set cookies passing the dynamic json key values. Using the https://github.com/js-cookie/js-cookie#json, it can be done easily. Wanted to store each selected option value of user in cookie, so it's not lost in case of tab or browser shutting down.

var json = { 
        option_values : {}
    };
    $('option:selected').each(function(index, el) {
        var option = $(this);
        var optionText = option.text();
        var key = 'option_' + index;
        json.option_values[key] = optionText;
        Cookies.set('option_values', json, { expires: 7 } );
    }); 

Then you can retrieve each cookie key value on each page load using

Cookies.getJSON('option_values');
-3

Closures work great for this.

function keyValue(key){
  return function(value){
    var object = {};
    object[key] = value;
    return object;
  }
}

var key = keyValue(key);
key(value);
2
  • Closure is merely the mechanism used here. The concept is HOF.
    – user663031
    Apr 17, 2017 at 17:12
  • 2
    HOF = Higher Order Functions.
    – Rick
    Apr 17, 2017 at 20:38
-3

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.