Reputation: 3521
I want loop through 1 to 21 and then use this loop numbers for getting an Array of Strings ['e1.wkh',...'e21.wkh']. But right now the only value I got is ['e21.wkh'].
function calculateStats() {
var obj = {}
var deviceId = "34534";
for (var i = 1; i <= 21; i++) {
var loo = i.toString();
console.log(loo);
obj[deviceId] = ['e' + loo + '.kwh'];
console.log(obj[deviceId]);
}
}
Upvotes: 0
Views: 84
Reputation: 36
Replace below line
obj[deviceId] = ['e' + loo + '.kwh'];
With
(obj[deviceId])?obj[deviceId].push('e' + loo + '.kwh'):obj[deviceId]=['e' + loo + '.kwh'];
Upvotes: 1
Reputation: 2584
Here is a possible solution:
The issue was you were overwriting your obj[deviceId].
function calculateStats() {
var obj = {}
var deviceId = "357803045265259@rayleigh";
obj[deviceId] = [];
for (var i = 1; i <= 21; i++) {
var loo = i.toString();
console.log(loo);
obj[deviceId].push('e' + loo + '.kwh');
console.log(obj[deviceId]);
}
}
https://jsfiddle.net/q651uhde/
Upvotes: 1
Reputation: 63524
Set up the array first and then push each string to it. No need to convert the index to a string as it will be coerced to a string when you push it to the array anyway.
function calculateStats() {
var obj = {};
var deviceId = "357803045265259@rayleigh";
obj[deviceId] = [];
for (var i = 1; i <= 21; i++) {
obj[deviceId].push('e' + i + '.kwh');
}
}
Upvotes: 0
Reputation: 262
function calculateStats() {
var obj = [];
var deviceId = "1111@rayleigh";
for (var i = 1; i <= 21; i++) {
var loo = i.toString();
console.log(loo);
obj.push('e' + loo + '.kwh');
}
console.log(obj);
} obj carries your array, is that what you want?
Upvotes: 0