How To Set A JS object property name from a variable
I am in need to set a JS object property name dynamically.
for(i=1; i<3; i++) {
var key = i+'name';
data = {
key : 'name1',
}
}
Result should be:
data = {
1name: 'name1'
2name: 'name1'
}
Solution 1:
var jsonVariable = {};
for(var i=1; i < 3; i++) {
jsonVariable[i + 'name'] = 'name' + i;
}
Solution 2:
You'll have to use []
notation to set keys dynamically.
var jsonVariable = {};
for(i=1; i<3; i++) {
var jsonKey = i+'name';
jsonVariable[jsonKey] = 'name1';
}
Now in ES6 you can use object literal syntax to create object keys dynamically, just wrap the variable in []
var key = i + 'name';
data = {
[key] : 'name1',
}
Solution 3:
With ECMAScript 6, you can use variable property names with the object literal syntax, like this:
var keyName = 'myKey';
var obj = {
[keyName]: 1
};
obj.myKey;//1
This syntax is available in the following newer browsers:
Edge 12+ (No IE support), FF34+, Chrome 44+, Opera 31+, Safari 7.1+
(https://kangax.github.io/compat-table/es6/)
You can add support to older browsers by using a transpiler such as babel. It is easy to transpile an entire project if you are using a module bundler such as rollup or webpack.