-1

This is my code, I have pushed the data into data[], but all the data showing the same content which is the last.

var myObj = {};
var data = [];

for (var kl = 0; kl < reportCriteriaIdData.length; kl++) {
    myObj["id"] = [myId];
    myObj[thisobj.scFilterLabel[0]] = [reportCriteriaIdData[kl].text];
    myObj["label"] = [reportCriteriaIdData[kl].text];
    myObj["index"] = [kl];
    data.push(myObj);
}
moopet
  • 6,014
  • 1
  • 29
  • 36
anu
  • 17
  • 4
  • 3
    You keep pushing a *reference* to one and the same object, which you keep modifying. You need to create a new `var myObj = {}` inside each loop iteration. – deceze Mar 30 '18 at 10:56
  • i am getting result like this: Controller : ["10.106.190.72"] id : ["10.106.190.72"] index : [1] label : ["10.106.190.72"] __proto__ : Object 1 : Controller : ["10.106.190.72"] id : ["10.106.190.72"] index : [1] label : ["10.106.190.72"] – anu Mar 30 '18 at 10:57
  • Brilliant Thanks – anu Mar 30 '18 at 10:58
  • Also check https://stackoverflow.com/questions/7522385/push-replaces-the-old-value-in-the-array – gurvinder372 Mar 30 '18 at 11:04

1 Answers1

0

You need to initialize an empty object inside the for loop so that each time a new object is created and pushed in the array:

var data = []; 

for(var kl = 0; kl< reportCriteriaIdData.length; kl++)
{  
  //initialize empty object
  var myObj = {};
  myObj["id"] = [myId];
  myObj[thisobj.scFilterLabel[0]] = [reportCriteriaIdData[kl].text];
  myObj["label"] = [reportCriteriaIdData[kl].text];
  myObj["index"] = [kl];
  data.push(myObj);

}
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62