-3

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?

Shalafister's
  • 761
  • 1
  • 7
  • 34

1 Answers1

1

This is a fairly classic problem. You're recycling the same object through each iteration of the loop so you're inserting the exact same object into the array.

To fix this, declare that internally:

var rows = [];
for (k = 0; k < 2; k++) {
  for (m = 1; m < 4; m++) {
    var exc_hash = {
      id: data[0][k]
    };

    exc_hash[(data[m][k][7])] = ((data[m][k][1][2] == 'OK') ? data[m][k][1][0] : data[m][k][1][2]);

    rows.push(exc_hash);
  }
}

console.log(rows);
tadman
  • 208,517
  • 23
  • 234
  • 262