Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get sum of value from Json Array in Angular2(Typescript)

I have a Json Response

"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?

like image 343
ananya Avatar asked Aug 23 '17 07:08

ananya


5 Answers

The correct way of using JavaScript's reduce function (which is also valid for TypeScript) would be:

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).

like image 96
Stephan Avatar answered Nov 14 '22 07:11

Stephan


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 !

// 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 :

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.

like image 36
Pac0 Avatar answered Nov 14 '22 06:11

Pac0


You can use observable reduce. If you have Http response then:

this.http.get('url')
    .map(response.carts.value)
    .map(res => res.Amt)
    .reduce((a, b) => a + b)
    .subscribe(res => console.log(res))
like image 5
Anton Lee Avatar answered Nov 14 '22 08:11

Anton Lee


let sum = 0;
    for (var i = 0; i < this.carts.value.length; i++) {
        sum+= this.carts.value[i].Amt;
    }
like image 2
N1gthm4r3 Avatar answered Nov 14 '22 06:11

N1gthm4r3


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;
}
like image 2
Wesley Coetzee Avatar answered Nov 14 '22 08:11

Wesley Coetzee