繁体   English   中英

将对象推送到数组时,新的 object 显示为 [[object],[object],[object]] 而不是 [object, object, object]

[英]When pushing objects to an array the new object shows up like [[object],[object],[object]] instead of [object, object, object]

这是我的 function:

addToCart(id) {
  var productToAdd = this.items.filter(function (item) {
    return item.id === id;
  })
  console.log(typeof(productToAdd));
  this.shoppingCart.push(productToAdd);
}

Typeof function 表示数据类型为'object'。 但是,生成的购物车 object 看起来像这样,这意味着数据 object 确实是 [object]。

[
  [
    {
      "id": 2,
      "category": "Snack",
      "name": "Slanty",
      "price": "50",
      "image": "https://www.beautifulworld.com/wp-content/uploads/2016/09/K2-Mountain.jpg"
    }
  ],
  [
    {
      "id": 6,
      "category": "Snack",
      "name": "Slanty",
      "price": "50",
      "image": "https://www.beautifulworld.com/wp-content/uploads/2016/09/K2-Mountain.jpg"
    }
  ]
]

减轻这种情况的最佳方法是什么? 我需要以[{},{},{}]形式而不是[[{}],[{}],[{}]]获取我的对象我知道这不是一个好问题,但我是新手javascript。

如果使用 push,则考虑推送单个元素。 如果要添加另一个数组的元素,请使用concat方法

您必须使用find而不是filter

addToCart(id) {
  var productToAdd = this.items.find(item => item.id === id);
  if (typeof(productToAdd) !== 'undefined') {
    this.shoppingCart.push(productToAdd);
  }
}

这很简单

//Assuming that 
 this.items= [ [ { "id": 2, "category": "Snack", "name": "Slanty", "price": "50", "image": "https://www.beautifulworld.com/wp-content/uploads/2016/09/K2-Mountain.jpg" } ], [ { "id": 6, "category": "Snack", "name": "Slanty", "price": "50", "image": "https://www.beautifulworld.com/wp-content/uploads/2016/09/K2-Mountain.jpg" } ] ]

this.shoppingCart=[];
this.items.forEach(item => {
 this.shoppingCart.push(item[0]);
});
console.log(this.shoppingCart) // this will be your resultant array

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM