这是我的函数:
addToCart(id) {
var productToAdd = this.items.filter(function (item) {
return item.id === id;
})
console.log(typeof(productToAdd));
this.shoppingCart.push(productToAdd);
}Typeof函数指示数据类型为'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新手。
发布于 2021-01-21 01:00:13
如果您使用push,则可以考虑推送单个元素。如果要添加另一个数组的元素,请使用concat方法
发布于 2021-01-21 01:08:30
您必须使用find而不是filter。
addToCart(id) {
var productToAdd = this.items.find(item => item.id === id);
if (typeof(productToAdd) !== 'undefined') {
this.shoppingCart.push(productToAdd);
}
}发布于 2021-01-21 01:14:28
这是非常简单的
//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 arrayhttps://stackoverflow.com/questions/65814028
复制相似问题