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

17,895

Solution 1

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.

Solution 2

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

Solution 3

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

Solution 4

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

Solution 5

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;
}
Share:
17,895
ananya
Author by

ananya

Updated on June 13, 2022

Comments

  • ananya
    ananya almost 2 years

    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?