TechGuy TechGuy - 18 days ago 5
HTML Question

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

Answer

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