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 .
You need to make the object first, then use [] to set it. var key = "happyCount"; var obj = {}; obj[key] = someValueArray; myArray. push(obj);
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With