[英]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.