如何从Angular2(Typescript)中的Json数组中获取值的总和

ana*_*nya 4 arrays json typescript angular

我有一个Json响应

"carts": {
            "value": [
                {

                    "Amt": 40

                },
                {
                    "Amt": 20.25

                },
                {

                    "Amt": 10.30

                }

            ]
        }
Run Code Online (Sandbox Code Playgroud)

我想得到Amt字段的和值,输出应该是70.55如何使用Typescript来获取它.我是打字稿的新手.有人可以帮我这个吗?

Pac*_*ac0 7

我非常赞成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);
Run Code Online (Sandbox Code Playgroud)

@Stefan发表评论后:

修复了错误,最好不要分配b的类型,以便从上下文中推断出b的类型,并可能在编译时引发Typescript错误。


Ste*_*han 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);
Run Code Online (Sandbox Code Playgroud)

请注意,如果要支持IE8,则必须包含polyfill(如MDN页面上的那样).


Ant*_*Lee 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))
Run Code Online (Sandbox Code Playgroud)


N1g*_*4r3 2

let sum = 0;
    for (var i = 0; i < this.carts.value.length; i++) {
        sum+= this.carts.value[i].Amt;
    }
Run Code Online (Sandbox Code Playgroud)