Reputation: 6852
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'
}
Upvotes: 217
Views: 180779
Reputation: 19592
With ES 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.
Upvotes: 146
Reputation: 1824
Use a variable as an object key
let key = 'myKey';
let data = {[key] : 'name1'; }
See How to iterete on your object here
Upvotes: 42
Reputation: 1
Along the lines of Sainath S.R's comment above, I was able to set a js object property name from a variable in Google Apps Script (which does not support ES6 yet) by defining the object then defining another key/value outside of the object:
var salesperson = ...
var mailchimpInterests = {
"aGroupId": true,
};
mailchimpInterests[salesperson] = true;
Upvotes: 0
Reputation: 97717
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',
}
Upvotes: 219
Reputation: 89
It does not matter where the variable comes from. Main thing we have one ... Set the variable name between square brackets "[ .. ]".
var optionName = 'nameA';
var JsonVar = {
[optionName] : 'some value'
}
Upvotes: 8
Reputation: 2174
This is the way to dynamically set the value
var jsonVariable = {};
for (var i = 1; i < 3; i++) {
var jsonKey = i + 'name';
jsonVariable[jsonKey] = 'name' + i;
}
Upvotes: 22
Reputation: 583
jsonVariable = {}
for(i=1; i<3; i++) {
var jsonKey = i+'name';
jsonVariable[jsonKey] = 'name1'
}
this will be similar to
jsonVariable = {
1name : 'name1'
2name : 'name1'
}
Upvotes: 1
Reputation: 7452
var jsonVariable = {};
for(var i=1; i < 3; i++) {
jsonVariable[i + 'name'] = 'name' + i;
}
Upvotes: 210