I'm trying to create an array of hashes in javascript. For instance;
[{id: "1", demo: 1, demo2: 2, demo3: 3}, {id: "2", demo: 1, demo2: 2, demo3: 3}, {id: "3", demo: 1, demo2: 2, demo3: 3}..]
I have loop through from 2 for loops but because the hash variable name is the same during the loop it writes on the previous one, not pushing it to array;
var rows = [];
var exc_hash = {};
for (k = 0; k < 2; k++) {
for (m = 1; m < 4; m++) {
var exc = ((data[m][k][1][2] == 'OK') ? data[m][k][1][0] : data[m][k][1][2]);
exc_hash["id"] = data[0][k];
exc_hash[(data[m][k][7])] = exc;
}
rows.push(exc_hash);
}
console.log(rows);
When I console log the rows, it prints;
[{id: "1", demo: 1, demo2: 2, demo3: 3}, {id: "1", demo: 1, demo2: 2, demo3: 3}]
The last hash written as for the first hash as well.
EDIT:
Thank you but when I use this like you show;
var rows = [];
for (k = 0; k < 2; k++) {
for (m = 1; m < 4; m++) {
var exc_hash = {
id: k
};
exc_hash['data'+m] = 'data'+m+k;
rows.push(exc_hash);
}
}
console.log(rows);
it prints;
0:{id: 0, data1: "data10"}
1:{id: 0, data2: "data20"}
2:{id: 0, data3: "data30"}
3:{id: 1, data1: "data11"}
4:{id: 1, data2: "data21"}
5:{id: 1, data3: "data31"}
However, I would like to get this;
0:{id: 0, data1: "data10", data2: "data20", data3: "data30"}
1:{id: 1, data1: "data11", data2: "data21", data3: "data31"}
How can I accomplish this?