javascript - 使用 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;
}
解决方案
使用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))
推荐阅读
- symfony - Symfony 请求在 EventSubscriber 中不可用
- python - 日期格式不正确.. 隐藏密码的方法??Excel、Python、Mysql
- xcode - 对于 Xcode 10.x 中的开发,git 集成与 github 的工作情况如何?
- python-3.x - 没有名为 cy_yolo_findboxes 的模块
- java - 实现 Nashorn ClassFilter 等价物
- javascript - 在 nightwatch.js 中的单个元素中断言多个值
- arrays - 在R中查找数组中最近元素的最快方法
- c - 在 C 函数中修改变量或结构
- c# - 如何在 .NET Core 2.x 中本地化 URL?
- python - 使用 BS,当某些迭代中缺少行时循环标记 python3