Hello,
Could anyone help with the handlebar syntax to use to get the sum of the `amount` elements in the JSON below?.....
Thank you in advance
Hello,
Could anyone help with the handlebar syntax to use to get the sum of the `amount` elements in the JSON below?.....
Hi, @davidgospel.
I got the intended result with this syntax:
{{add applied_discounts.0.amount applied_discounts.1.amount applied_discounts.2.amount}}
Of course, that’s assuming you already know the number of array items.
Handlebars statements aren’t designed for variable assignment. To keep a new sum available in your flow, you would have to assign the value resolved above to a new or existing field or JavaScript variable.
Hi Stephen,
Thanks for the quick response.
Unfortunately we don't know the size of the `applied_discounts` array.
So do you know what syntax could be used when the size of the array is unknown?
Good question. I tried all the obvious handlebars solutions: looping, nesting, the sum function...and Help Center and Google searches.
Unfortunately, there doesn't seem to be a built-in answer for this particular question. I'd love to hear how others have attacked the problem.
Here's where you might go from here:
{{add applied_discounts.0.amount applied_discounts.1.amount applied_discounts.2.amount applied_discounts.3.amount applied_discounts.4.amount}}
Hi Stephen,
Thanks for looking into this.
Funnily enough, I came to the same solution: just include many elements in the Add helper.
I assume this helper includes a check to see if a value exists before performing the add function.
Also, I was able to include the Add helper within my existing handlebars - which calculates the Item Rate to send to NetSuite.
This Rate value includes any discounts applied to an order in Big Commerce
Here is my full handlebars....
{{#if products[*].applied_discounts.0.amount}} {{subtract products[*].price_ex_tax (divide (add products[*].applied_discounts.0.amount products[*].applied_discounts.1.amount products[*].applied_discounts.2.amount products[*].applied_discounts.3.amount) products[*].quantity)}} {{else}} {{products[*].price_ex_tax}} {{/if}}
@davidgospel: That's a master class in handlebars. Thanks, and I hope others can benefit from it as well.
>I assume this helper includes a check...
From my limited tests, it seems that an undefined array element behaves like an empty variable and it's added +0, with no harm. Don't try this hack in JavaScript. ;)