jQuery对象替换数组中的值

时间:2018-06-29 17:09:08

标签: jquery json

我正在将产品创建为jquery中的对象并将其放入数组中,但是结果是两个相同的。如果我举个例子,很容易理解。

var product = {
  id: 0,
  name: 'Tomato',
  price: 500
};

var array_products = new Array();

//each loops 2
$.each(data, function(i, item) {
  var new_product = product;
  new_product.id = i;
  new_product.name = "new Tomato " + i;
  new_product.price = 700;

  array_products.push(new_product);
});

console.log(array_products);

结果:

0: {
  id: 1,
  name: "new Tomato 1",
  price: 700
}
1: {
  id: 1,
  name: "new Tomato 1",
  price: 700
}

这里的问题是当我“创建”新产品时,在第二个循环中,替换数组中位置0的值。结果是两个相等的乘积,而不是两个不同的乘积。我在做什么错了?

2 个答案:

答案 0 :(得分:3)

您可以使用map()执行类似的简单翻译。同样,为了使对象不同,您每次都必须创建一个新对象。要么通过创建并更改它,或者可以简单地使用稍后分配给它的值来创建它。

var array_products = $.map(data, function(i, item) {
  return {
    id: i,
    name: 'product_'+ i,
    price: 500
  };
});

console.log(array_products);

答案 1 :(得分:1)

您只需要更改对象定义。

var product = function Product(){
    this.id = null;
    this.name = null;
    this.price = null;
}

您的循环变为:

$.each(data, function(i, item) {
  var new_product = new product();
  new_product.id = i; 
  new_product.name = 'new Tomato '+i;
  new_product.price = 700;
  array_products.push(new_product);
});

如果要克隆现有对象并更改一些属性,则循环将为:

var new_product = Object.assign({}, existingProductObject); ;
new_product.id = i; 
array_products.push(new_product);

Here is a working sample