首页 > 解决方案 > 使用 typescript 遍历 json 响应和一些总账单

问题描述

我正在尝试在打字稿的订单列表中汇总所有总账单,但它不起作用,它说对象的类型为“未知”。当我试图访问总账单时。它在浏览器控制台中工作正常,但在可视代码上它会抛出错误。

这是我的json回复

{
    "order_list": {
       
            "32212000000037": {
                "invoice_id": "32212000000037",
                "customer_id": "006019000015",
                "customer_name": "Spantik",
                "inv_date": "2020-12-24",
                "prod_date": "2020-12-24",
                "inv_time": "09:00",
                "total_bill": 22,
                "notification": "waiting",
                "sales_id": "",
                "inv_type": "regular",
                "danger": "over"
            },
            "32212000000036": {
                "invoice_id": "32212000000036",
                "customer_id": "006019000015",
                "customer_name": "Spantik",
                "inv_date": "2020-12-24",
                "prod_date": "2020-12-24",
                "inv_time": "14:57",
                "total_bill": 22,
                "notification": "waiting",
                "sales_id": "",
                "inv_type": "regular",
                "danger": "over"
            }        
    },
}

这是我正在尝试的

countTotalBill(orderDate: string) {
  let totalBill = 0;

  const itemList = this.orderLists[orderDate];

  if (itemList != null) {
    const arr = Object.values(itemList);

    arr.filter(ele => {
      totalBill = totalBill + ele.total_bill; // <<<<<<======= here is the problem
    });
  }

  return totalBill;
}

标签: javascripttypescriptvue.js

解决方案


使用reduce代替过滤器,

totalBill = arr.reduce((acc,cur)=>acc + cur.total_bill,0)

类型:

const apiResp = {
    order_list: {
        "32212000000037": {
            invoice_id: "32212000000037",
            customer_id: "006019000015",
            customer_name: "Spantik",
            inv_date: "2020-12-24",
            prod_date: "2020-12-24",
            inv_time: "09:00",
            total_bill: 22,
            notification: "waiting",
            sales_id: "",
            inv_type: "regular",
            danger: "over",
        }
    },
};

interface OrderItem {
    [key:string]:string|number;
    total_bill: number;
}

const arr:OrderItem[] = Object.keys(apiResp).map(x=>apiResp[x])

console.log(arr.reduce((acc,cur)=>acc + cur.total_bill,0))

推荐阅读