JS将对象推送到变量将最后一个对象添加到所有元素

时间:2016-02-25 17:14:06

标签: javascript object push

我正在尝试这个,

 var coProducts = {0:{id:"nsdn",variant:"kjdfhnkjsd",price:"sdfd",quantity:"hbsdjh"},
                   1:{id:"abc",variant:"def",price:"ghi",quantity:"ijk"}};
        var basketProds = new Object();
        var arrBasketProds = [];
        var i;
        for(i in coProducts) { 
           if (coProducts.hasOwnProperty(i)) {
                basketProds.ProductID = coProducts[i].id;
                basketProds.VariantID = coProducts[i].variant;
                basketProds.Price = coProducts[i].price;
                basketProds.quantity = coProducts[i].quantity;
                arrBasketProds.push(basketProds);
           }
        }

        pageProperties = {
            Currency: "EUR",
            Products: arrBasketProds
        }

现在arrBasketProds:给我以下结果

      Currency: "EUR"
      Products: Array[2]
                0: Object
                   Price: "abc"
                   ProductID: "def"
                   VariantID: "ghi"
                   quantity: "ijk"

                1: Object
                   Price: "abc"
                   ProductID: "def"
                   VariantID: "ghi"
                   quantity: "ijk"

但我希望coAroducts的值都可以在arrBasketProds中找到。

1 个答案:

答案 0 :(得分:1)

您需要在每次迭代中初始化basketProds = new Object();



var coProducts = {
  0: {
    id: "nsdn",
    variant: "kjdfhnkjsd",
    price: "sdfd",
    quantity: "hbsdjh"
  },
  1: {
    id: "abc",
    variant: "def",
    price: "ghi",
    quantity: "ijk"
  }
};
var basketProds;
var arrBasketProds = [];
var i;
for (i in coProducts) {
  if (coProducts.hasOwnProperty(i)) {
    basketProds = new Object();     // This creates a new object.
    basketProds.ProductID = coProducts[i].id;
    basketProds.VariantID = coProducts[i].variant;
    basketProds.Price = coProducts[i].price;
    basketProds.quantity = coProducts[i].quantity;
    arrBasketProds.push(basketProds);
  }
}

pageProperties = {
  Currency: "EUR",
  Products: arrBasketProds
}
console.log(arrBasketProds);