Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

People also ask

Can I use variable as object key JavaScript?

Use Variable as Key for Objects in JavaScript log(obj. key); console. log(obj["key"]); The variable varr was set as the key for the object obj .

How do you use a variable name as a key in an object JavaScript?

You need to make the object first, then use [] to set it. var key = "happyCount"; var obj = {}; obj[key] = someValueArray; myArray. push(obj);

How can you get the value in an object's key using a variable referencing key?

To get value in an object's key using a variable referencing that key with JavaScript, we can use square brackets. console. log(obj[name]); to get the name property of the obj object with obj[name] .


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.


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

Solution:

var key = "anything";

var json = {};

json[key] = "key attribute";