How add object to array jQuery

30,566

Solution 1

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

Solution 2

My arrToServer have 2 identical objetcs, why?

Because you are only creating one object, outside the loop, and push the same object to the array multiple times. Passing an object to a function or assigning it to a different variable does not create a copy of the object.

Create the object inside the loop (and with loop I mean the .each callback).

Here is an example using .map, which is much cleaner IMO:

var arrToServer = $("input[type=checkbox]:checked").map(function() {
    return {
        CategoryId: categoryId,
        EnteredDate: enteredDate,
        SystemDate: systemDate,
        EmpId: empId,
        ProductId: $(this).attr('id')
    };
}).get();
Share:
30,566
okrupovich
Author by

okrupovich

Updated on July 09, 2022

Comments

  • okrupovich
    okrupovich almost 2 years

    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?

  • SpaceNinja
    SpaceNinja over 8 years
    Can you please explain why there is a .get() at the end of your example?
  • Felix Kling
    Felix Kling over 8 years
    .get returns an array. Without it, you would be working with a jQuery object.
  • SpaceNinja
    SpaceNinja over 8 years
    Ah thank you. When I searched, I saw this which referred to Ajax: api.jquery.com/jquery.get. Thanks!