6

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?

6 Answers 6

7

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

Sign up to request clarification or add additional context in comments.

Comments

7

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.

6 Comments

That won't work this way since the items in value and thus your b and your initial value (your first a) are objects.
@Stefan You are right, and forgot the '0' initial value as well. Editing.
Just an additional note: I wouldn't type annotate a and b and let TypeScript infer the types. Otherwise for example if the objects in value don't contain any Amt values using any as type hides the resulting error.
Can you elaborate ? I thought any was the actual "default" if nothing was indicated (and no type guards or like are used). (without the noImplicitAny option, which is the default)
At assignments types are automatically inferred (e.g. let x = 0;). If a function definition contains the definition of the callback parameters, those are also automatically inferred (for example the relevant definition for reduce is reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;). typescriptlang.org/docs/handbook/type-inference.html contains useful information about that.
|
5

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

Comments

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

Comments

2

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;
}

1 Comment

That won't work since e will be an object. Additionally if you want e to be a number it would be better to type annotate it as a number, not any. That way there would be at least a compiler error (which is one aspect why you use TypeScript) if you supply it with an object.
1

This is the basic way to do it.

  sum=0;
  for(let a of json.carts.value){
      sum=sum+a.Amt;
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.