4

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?

1
  • Here's a fiddle that may make the behavior clearer: jsfiddle.net/FcHpK Commented Feb 25, 2014 at 18:10

2 Answers 2

4

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);
});
Sign up to request clarification or add additional context in comments.

Comments

3

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

3 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.