【问题标题】:calculating the invoice total and invoice quantity from an array of objects in react从反应中的一组对象计算发票总额和发票数量
【发布时间】:2021-08-12 10:40:19
【问题描述】:

我在 react 中有在线购物应用程序。我在该数组中有名为 invItems 的发票数组和名为 items 的产品。我想计算invItems 数组中所有商品的价格*数量。 此外,我想计算发票中所有对象(项目)的总数量。 代码如下:

useEffect(()=>{
if(invItems.length>0){
  var invtotal=0.0;
  var total=invItems.reduce((invTotal,x)=>(invTotal+=x.total));
  var sum=0;
   sum=invItems.reduce((sum,x)=>(sum+=x.qty));
  console.log("result:",total,sum );
}
  
},[invItems])
console.log("invItems:",invItems);

每个Item都是如下的对象:

const newItem={
    OId:'',
    productId: '',
    productName: '',
   productCode: '',
    qty:1,   
    price: 0.0,
    total:0.0,
}

结果不正确或格式不正确请在屏幕截图中查看控制台。

【问题讨论】:

标签: javascript arrays reactjs invoice


【解决方案1】:

我正在分享,以便它可能对任何人都有帮助。 以下更改解决了我的问题。它计算所有invItems 的总数和数量。

useEffect(()=>{
if(invItems.length>0){
  var invtotal=0.0;  //(a,v)=>a+v.credit,0
  var total=invItems.reduce((a,x)=>a+x.total,0);
  var sum=0;
   sum=invItems.reduce((a,x)=>a+x.qty,0);
  console.log("result:",total,sum );
}
  //setVal({...val,total:total,qty:qty})
},[invItems])

最好的问候

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 2021-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    相关资源
    最近更新 更多