How do I create a sum of values from an API response?

I want to add statistics in my app which show Sum of values from various api calls.

Here is a sample.

I want to be able to show the sum of all values of "bcy_total" if "account_name" == "Cost of Goods Sold"

How would i go about doing this? Really appreciate the help

Hi @Isv!

You could do this using a couple different methods. Here's one using single line JS directly in a Statistic component:

{{ formatDataAsArray(query1.data).filter(obj => obj.rental_duration == 6).map(obj => obj.length).reduce((sum, obj) => sum + obj) }}

I'm using .filter to filter my query data to find the rows with rental_duration equal to 6, using .map to only grab the length column from those rows, then summing the length column using .reduce

Your example might be something like:

{{ ZohoGetExpenses.filter(obj => obj.account_name == "Cost of Goods Sold").map(obj => obj.bcy_total).reduce((sum, obj) => sum + obj) }}

Let me know if you have any questions or if this works for you!

1 Like

Thanks a ton @victoria

this worked. And more than anything, thnks for explaining what you did there.

1 Like

Quick follow up.

What if the value i was trying to sum up was placed as a string instead of a number. Where in the formula would be the best place to convert to number?

Awesome! :slightly_smiling_face::raised_hands:

You should be able to use the parseint(string) function to surround obj in the reduce function, or you could tack on another .map function after the first .map function to do something like .map(str => parseInt(str))

Since our JS is getting a little long, you might also find some benefit in creating a JS transformer and just writing this logic out there (in more than just one line :sweat_smile:) and referencing {{your_transformer.value}} in your component value field.