TechGuy
TechGuy

Reputation: 4560

Jquery Array duplicate records inside the tr iterate

My Table & Code

NewsNo GeoLoc
------ ------
1       US
2       UK
3       GER


var GloablArr = [];

$("#btnRefUp").click(function () {

   var newssArr = {};
    $("#ntbl > tbody > tr").each(function () {

        newssArr['NewsNo']  = $(this).find('td :eq(0)').val();
        newssArr['GeoLoc']  = $(this).find('td :eq(1)').val();

        GloablArr.push(newssArr) <-- GlobalArr shows the final item(s) only.

    });

});

But my results come like this(GlobalArr),
3 GER
3 GER
3 GER

Upvotes: 1

Views: 34

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115222

You are updating the same object again and again instead you need to initialize object inside the callback function of each method.

var GloablArr = [];

$("#btnRefUp").click(function() {
  $("#ntbl > tbody > tr").each(function() {
    var newssArr = {};
    newssArr['NewsNo'] = $(this).find('td :eq(0)').val();
    newssArr['GeoLoc'] = $(this).find('td :eq(1)').val();
    GloablArr.push(newssArr) 
  });
});

Or directly generate object and push to the array.

var GloablArr = [];

$("#btnRefUp").click(function() {
  $("#ntbl > tbody > tr").each(function() {
    GloablArr.push({
      NewsNo: $(this).find('td :eq(0)').val(),
      GeoLoc: $(this).find('td :eq(1)').val()
    })
  });
});

You can even simplify the code by using map() method instead of each() method.

var GloablArr;

$("#btnRefUp").click(function() {
  GloablArr = $("#ntbl > tbody > tr").map(function() {
    return {
      NewsNo: $(this).find('td :eq(0)').val(),
      GeoLoc: $(this).find('td :eq(1)').val()
    };
  }).get(); // get the result as array
});

Upvotes: 1

Jamiec
Jamiec

Reputation: 136104

You're only ever creating a reference to newsArr - thereafter you're pushing the same properties to it and pushing another reference each time to your global array.

A simple fix is to recreate a new object each iteration of each

$("#ntbl > tbody > tr").each(function () {
    var newssArr = {};
    newssArr['NewsNo']  = $(this).find('td :eq(0)').val();
    newssArr['GeoLoc']  = $(this).find('td :eq(1)').val();

    GloablArr.push(newssArr) <-- GlobalArr shows the final item(s) only.

});

A better solution might be to just create all the items for your global array in 1 go

var items = $("#ntbl > tbody > tr").map(function () {
    return {
     NewsNo: $(this).find('td :eq(0)').val(),
     GeoLoc: $(this).find('td :eq(1)').val()
    };
}).get();
GloablArr = items;

Upvotes: 1

Related Questions