如何将对象添加到数组 jQuery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22022429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 01:47:46  来源:igfitidea点击:

How add object to array jQuery

jqueryobjecteach

提问by okrupovich

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?

我的 arrToServer 有 2 个相同的对象,为什么?

采纳答案by Satpal

create a copy of object then set project id.

创建对象的副本,然后设置项目 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);
});

回答by Felix Kling

My arrToServer have 2 identical objetcs, why?

我的 arrToServer 有 2 个相同的对象,为什么?

Because you are only creating oneobject, 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 insidethe loop (and with loop I mean the .eachcallback).

在循环创建对象(循环是指.each回调)。

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

这是一个使用 的示例.map,IMO 更简洁:

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