Sum of Key Values

I have an optimistic save process and would like to keep a running total of some key values without sending the model to FM. What is the JS to do this?

So a count of key values in a given object?

You could do Object.keys(obj).length. How often do you want to update this value?

If you mean a sum of values, do you need to loop through an object/array and get a total?

Correct, just need the sum of all key values of an array. No need to loop

To make sure I’m on the same page, lets say we have an array:

"myArray": [{
        "value": 4
    }, {
        "value": 5

Do you want the count of keys in the array? (2)

Or do you want the sum of the values? (9)

If the latter, the script for that would look something like:

var total = 0

model.myArray.forEach(function(o) {
    total += o.value

That works for
adding but not so much for removing, any thoughts.

chrome-capture-2022-2-23 (1)

I see, you essentially want to run a “recalculate” named action whenever something is changed (a checkbox was clicked). Set a variable to 0 at the start of the script, do your calculations, and then update the model with the new value at the end.

Thanks Andrew
InvTotal (3)

1 Like