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]);
}
}
asked Jun 22, 2015 at 11:36
RegarBoy
3,5411 gold badge26 silver badges47 bronze badges
4 Answers 4
Replace below line
obj[deviceId] = ['e' + loo + '.kwh'];
With
(obj[deviceId])?obj[deviceId].push('e' + loo + '.kwh'):obj[deviceId]=['e' + loo + '.kwh'];
Sign up to request clarification or add additional context in comments.
Comments
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]);
}
}
answered Jun 22, 2015 at 11:40
Arathi Sreekumar
2,5841 gold badge19 silver badges29 bronze badges
5 Comments
RegarBoy
obj[deviceId] should be equal to the array of 'e' + loo + '.kwh'
Arathi Sreekumar
I have updated with a jsfiddle. It is an array of 'e' + loo + '.kwh'.
RegarBoy
I have got such an error: Uncaught TypeError: Cannot read property 'push' of undefined
Arathi Sreekumar
Did you add this line before the for loop: obj[deviceId] = []; ?
RegarBoy
Alright it is working and both the ternary operation : (obj[deviceId])?obj[deviceId].push('e' + loo + '.kwh'):obj[deviceId]=['e' + loo + '.kwh'];
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?
answered Jun 22, 2015 at 11:40
ibrahimbayer
3621 silver badge9 bronze badges
Comments
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');
}
}
answered Jun 22, 2015 at 11:43
Andy
63.7k13 gold badges72 silver badges99 bronze badges
Comments
lang-js
deviceIdas the element name here:obj[deviceId] = ['e' + loo + '.kwh'];So you always overwrite the last value ofobj[deviceId]How should the elements be named instead?