skip to Main Content

I need help summing all the numbers from JSON that I get from an API response and saving them in a variable that I can output in template…

This is what my JSON that I get looks like:

[
    {
        "count": 495,
        "label": "Ticket",
        "user_id": "42807"
    },
    {
        "count": 248,
        "label": "Hotel",
        "user_id": "42807"
    },
    {
        "count": 75,
        "label": "Insurance",
        "user_id": "42807"
    },
]

This is how I’m getting the data from service in my component.ts file:

  noOfPurchases: number;

  getSingleCustomerPurchases() {
    const id = Number(this.route.snapshot.paramMap.get('id'));
    this.customerService.getSingleCustomerPurchases(id).subscribe(
      data => {
        this.purchasedProd = data;
        // console.log(this.purchasedProd);
      },
      error => {
        console.log('Error', error);
      });
  }

I have tried using .map function but I was getting the error Property ‘map’ does not exist on type ‘number’. How would I go about summing all the numbers of "count" together?

2

Answers


  1. You can use reduce array method

    this.purchasedProd = data.reduce((acc, curr) => acc += curr.count, 0)
    
    Login or Signup to reply.
  2. In your’s component declare a variable which you would like to use in template
    public countSum:number = 0
    Then in the subscription you do it like that:

    getSingleCustomerPurchases() {
        const id = Number(this.route.snapshot.paramMap.get('id'));
        this.customerService.getSingleCustomerPurchases(id).subscribe(
          data => {
            this.purchasedProd = data;
            this.countSum = 0;
            this.purchasedProd.forEach(value => this.countSum += value.count)
          },
          error => {
            console.log('Error', error);
          });
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search