我有一个Json响应
"carts": {
"value": [
{
"Amt": 40
},
{
"Amt": 20.25
},
{
"Amt": 10.30
}
]
}
我想得到Amt字段的和值,输出应该是70.55 如何使用Typescript来获取它。我是打字稿的新手。 有人可以帮我这个吗?
答案 0 :(得分:6)
使用JavaScript reduce函数(对TypeScript也有效)的正确方法是:
const response = {
"carts": {
"value": [
{
"Amt": 40
},
{
"Amt": 20.25
},
{
"Amt": 10.30
}
]
}
};
const total = response.carts.value.reduce((sum, item) => sum + item.Amt, 0);
console.log(total);

请注意,如果你想支持IE8,你必须包含一个polyfill(就像MDN's page上那样)。
答案 1 :(得分:5)
您可以使用observable reduce。 如果您有Http响应,那么:
this.http.get('url')
.map(response.carts.value)
.map(res => res.Amt)
.reduce((a, b) => a + b)
.subscribe(res => console.log(res))
答案 2 :(得分:5)
我非常支持Rxjs' Observable answer,但由于没有人提及它: Javascript数组有reduce
函数,因此可以在Typescript中使用它也是!
// suppose variable carts already stores the deserialized json
let total: number = carts.value.reduce(
(a: number, b) => a + b.Amt, 0);
在@Stefan的评论之后:
修正错误& 最好不要分配b的类型,以便从上下文中推断它,并且可能在编译时引发Typescript错误。
答案 3 :(得分:2)
let sum = 0;
for (var i = 0; i < this.carts.value.length; i++) {
sum+= this.carts.value[i].Amt;
}
答案 4 :(得分:2)
您可以编写如下函数:
public cartTotal(): number {
let total: number = 0;
this.carts.value.forEach((e:any) => {
total = total + Number(e.Amt);
});
return total;
}
答案 5 :(得分:0)
这是完成这项工作的基本方法。
sum=0;
for(let a of json.carts.value){
sum=sum+a.Amt;
}