如何从 Angular2(Typescript) 中的 Json 数组获取值的总和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45833340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get sum of value from Json Array in Angular2(Typescript)
提问by ananya
I have a Json Response
我有一个 Json 响应
"carts": {
"value": [
{
"Amt": 40
},
{
"Amt": 20.25
},
{
"Amt": 10.30
}
]
}
I want to get the sum value of Amt field and the output should be 70.55 How to get this using Typescript.I am new to typescript. Can anyone please help me with this?
我想获取 Amt 字段的总和值,输出应为 70.55 如何使用 Typescript 获取此值。我是 typescript 的新手。任何人都可以帮我解决这个问题吗?
回答by Pac0
I am very much in favor of the Rxjs' Observable answer, but since no one else mentioned it : Javascript arrays have a reduce
function, so one can use it in Typescript too !
我非常赞成Rxjs 的 Observable 答案,但因为没有其他人提到它:Javascript 数组有一个reduce
函数,所以也可以在 Typescript 中使用它!
// suppose variable carts already stores the deserialized json
let total: number = carts.value.reduce(
(a: number, b) => a + b.Amt, 0);
after @Stefan's comments :
在@Stefan 发表评论后:
Fixed mistakes & better to not assign type of b, so that it will be inferred from the context and maybe raise a Typescript error at compile-time.
修复了错误并且最好不要分配 b 的类型,以便从上下文中推断出它并可能在编译时引发 Typescript 错误。
回答by Stephan
The correct way of using JavaScript's reducefunction (which is also valid for TypeScript) would be:
使用 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);
Note that if you want to support IE8 you have to include a polyfill (like that on MDN's page).
请注意,如果您想支持 IE8,您必须包含一个 polyfill(就像MDN 页面上的那样)。
回答by Anton Lee
You can use observable reduce. If you have Http response then:
您可以使用可观察的减少。如果您有 Http 响应,则:
this.http.get('url')
.map(response.carts.value)
.map(res => res.Amt)
.reduce((a, b) => a + b)
.subscribe(res => console.log(res))
回答by N1gthm4r3
let sum = 0;
for (var i = 0; i < this.carts.value.length; i++) {
sum+= this.carts.value[i].Amt;
}
回答by Wesley Coetzee
You can write a function like this:
你可以写一个这样的函数:
public cartTotal(): number {
let total: number = 0;
this.carts.value.forEach((e:any) => {
total = total + Number(e.Amt);
});
return total;
}
回答by marouane kadiri
This is the basic way to do it.
这是执行此操作的基本方法。
sum=0;
for(let a of json.carts.value){
sum=sum+a.Amt;
}