简体   繁体   中英

Javascript, creating array of hashes writes same hash

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM