[英]Add multiple object values with the same key from object array using forEach in JavaScript
I am working on a shopping basket feature using Vue JS, I need to create a subtotal feature which multiplies the price and quantity values of each item and adds them together to create a subtotal. 我正在使用Vue JS开发购物篮功能,我需要创建一个小计功能,该功能将每个商品的价格和数量值相乘并将它们加在一起以创建小计。
dataSet: [
{
"instock" : '',
"price": 49,
"qty": 1,
"subTotal": ''
},
{
"instock" : '',
"price": 29,
"qty": 1,
"subTotal" : '',
},
]
I have managed to return the values for each of the 'price' and 'qty' using forEach on the object array like so: 我设法在对象数组上使用forEach返回“价格”和“数量”中每个值,如下所示:
getSubTotal(dataSet) {
this.dataSet.forEach(function(data) {
console.log(data.price)
})
console
49
29
So far so good (I think), I am getting the price values returned to me, the only problem is that they are not being return in the same array but seperately. 到目前为止,一切都很好(我认为),我正在获得返回给我的价格值,唯一的问题是它们不是以相同的数组返回而是分开返回。 I really need them to be returned as [49,29] so I am able add the values together for the subtotal.
我确实需要将它们返回为[49,29],因此我可以将这些小计的值加在一起。 I am able to hard code each array by index then add them seperately but this does not future proof the eventuality of a new clothing item in the object array.
我能够按索引对每个数组进行硬编码,然后分别添加它们,但是这并不能在将来证明对象数组中新服装的可能性。
Any advice/criticism or help would be greatly appreciated. 任何建议/批评或帮助将不胜感激。
getSubTotal(dataSet) { return this.dataSet.map(function(data) { return data.price; })
Okay so I was able to figure this out. 好吧,我能够弄清楚这一点。
dataSet: [
{
"price": 49,
"qty": 1,
},
{
"price": 29,
"qty": 1,
},
]
subTotals(data) {
const calcArray = [data.price, data.qty];
return calcArray.reduce((a,b)=> {
//multiply price by quantity for subtotal
return a*b;
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.