我有一个对象数组,在对象中有这样的数组
[
{
orderId: 123, orderStatus: 'Pending', date: 'june 13, 2020',
products: [ {product: 'choco', price: 300, qty: 3}, {product: 'milk', price: 350, qty: 2} ]
},
{
orderId: 124, orderStatus: 'Pending', date: 'june 13, 2020',
products: [ {product: 'butter', price: 100, qty: 1}, {product: 'milk', price: 350, qty: 2} ]
}
]
我想对产品的所有价格和数量求和(结果应该是2400(。有没有办法做到这一点?我正在使用 React js 和 firestore 作为数据库。
您还可以使用map,reduce和平面函数,如下所示:
const data = [
{
orderId: 123, orderStatus: 'Pending', date: 'june 13, 2020',
products: [ {product: 'choco', price: 300, qty: 3}, {product: 'milk', price: 350, qty: 2} ]
},
{
orderId: 124, orderStatus: 'Pending', date: 'june 13, 2020',
products: [ {product: 'butter', price: 100, qty: 1}, {product: 'milk', price: 350, qty: 2} ]
}
]
const pricesArray = data.map(item=>item.products.map(product=>product.price*product.qty));
console.log(pricesArray.flat().reduce((acc,sum)=>acc+sum));
标题
const data = [{orderId: 123, orderStatus: 'Pending', date: 'june 13, 2020',products: [{ product: 'choco', price: 300, qty: 3 }, { product: 'milk', price: 350, qty: 2 }]},{orderId: 124, orderStatus: 'Pending', date: 'june 13, 2020',products: [{ product: 'butter', price: 100, qty: 1 }, { product: 'milk', price: 350, qty: 2 }]}]
let sum = 0;
for (let i = 0; i < data.length; i++) {
for (let j = 0; j < data[i].products.length; j++) {
sum += data[i].products[j].price * data[i].products[j].qty
}
}
console.log(sum);