我试图显示购物篮中有多少商品,因此每个商品都有 qtyField: value
,而不是显示购物篮的 arr.length
。
就像在电子商务中一样,如果您的篮子里有 1 个苹果,篮子数量反射(reflect)了您拥有的商品数量。
var updateCartItem = {
Products: [
{
"product_idField":"96031",
"skuField":"321005Y-00100-ITM",
"nameField":"Cooper Sunglasses",
"priceField":"75.0000",
"qtyField":3,
"qtyFieldSpecified":true,
"$$hashKey":"object:8"
},
{
"product_idField":"another",
"skuField":"another-ITM",
"nameField":"Pony Sunglasses",
"priceField":"75.0000",
"qtyField":1,
"qtyFieldSpecified":true,
"$$hashKey":"object:8"
},
{
"product_idField":"empty",
"skuField":"empty-ITM",
"nameField":"Nobody wants it Sunglasses",
"priceField":"75.0000",
"qtyField":1,
"qtyFieldSpecified":true,
"$$hashKey":"object:8"
}
]
}
updateCartItem.Products.forEach(function (element) {
console.log(element.qtyField);
}, this);
在上面的对象中,有 3 个项目,但 qtyField
的数量不同,因此我想添加所有 qtyField
值并显示总数。
最佳答案
您可以使用reduce :
var updateCartItem = {
Products: [
{
"product_idField":"96031",
"skuField":"321005Y-00100-ITM",
"nameField":"Cooper Sunglasses",
"priceField":"75.0000",
"qtyField":3,
"qtyFieldSpecified":true,
"$$hashKey":"object:8"
},
{
"product_idField":"another",
"skuField":"another-ITM",
"nameField":"Pony Sunglasses",
"priceField":"75.0000",
"qtyField":1,
"qtyFieldSpecified":true,
"$$hashKey":"object:8"
},
{
"product_idField":"empty",
"skuField":"empty-ITM",
"nameField":"Nobody wants it Sunglasses",
"priceField":"75.0000",
"qtyField":1,
"qtyFieldSpecified":true,
"$$hashKey":"object:8"
}
]
}
var total = updateCartItem.Products.reduce((acc,prod) => {
return acc + prod.qtyField
}, 0);
console.log(total);
关于javascript - 如何在 JavaScript 中添加对象数组中的所有数量字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44573349/