Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How add object to array jQuery

I'm try add my objects to array, but on finish I have all identical objects

$('#Create').click(function(event) {
  event.preventDefault();

  var categoryId = $('#CatId').val();
  var enteredDate = $('#datepicker').val();
  var empId = $('#employeeID').text();
  var systemDate = $.datepicker.formatDate('dd.mm.yy', new Date());
  var obj = {
    CategoryId: categoryId,
    EnteredDate: enteredDate,
    SystemDate: systemDate,
    EmpId: empId
  };
  var arrToServer = [];
  var list = new Array();
  $("input[type=checkbox]:checked").each(function() {
    var productId = $(this).attr('id');
    obj.ProductId = productId;
    arrToServer.push(obj);                
  });
  arrToServer = JSON.stringify(arrToServer);
}

My arrToServer have 2 identical objetcs, why?

like image 703
okrupovich Avatar asked Mar 20 '23 11:03

okrupovich


1 Answers

create a copy of object then set project id.

$("input[type=checkbox]:checked").each(function () {
    var productId = $(this).attr('id');
    var clonedobj = jQuery.extend({}, obj); //create a shallow
    clonedobj.ProductId = productId;
    arrToServer.push(clonedobj);
});
like image 64
Satpal Avatar answered Mar 29 '23 14:03

Satpal