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
You can use reduce array method
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: