Sum of object values

Hi All,

I'm working on a project to monitor my test crypto trading bots. And there is one thing left I didn't succeed in fixing.

The bot output is sending me all current positions, in my case 1 to a maximum of 15. But I need some way to make a sum and present me with one total value :slight_smile:

In this case, I want to calculate the sum of,
payload.currentPositions.DCA[0].totalCost
payload.currentPositions.DCA[1].totalCost
payload.currentPositions.DCA[2].totalCost
can be up to payload.currentPositions.DCA[15].totalCost

How can I calculate this within a function?

Thanks!

You should be able to use Array.reduce() for this. Array.prototype.reduce() - JavaScript | MDN

Or Jsonata in a change node.
example expression

$sum(payload.currentPositions.DCA[].totalCost)

Epic! This is an eye-opener for me.. Thanks @E1cid and @Colin

Unfortunately I could not make it work with the Jsonata because I have to send all data in one session to my spreadsheet, and I could not join both Jsonata's in the change node..

So I had another look at @Colin his example, but have some difficulties with this one. I tried:

let initialValue = 0
let sum = [{x: msg.payload.currentPositions.DCA[0].currentValue}, {x: msg.payload.currentPositions.DCA[1].currentValue}, {x: msg.payload.currentPositions.DCA[2].currentValue}, {x: msg.payload.currentPositions.DCA[3].currentValue}].reduce(function (accumulator, currentValue) {
return accumulator + currentValue.x
}, initialValue)

msg.payload ={};
msg.payload = sum

But there are between 0 and 15 DCA's open at a certain time, so I could just add the msg.payload.currentPositions.DCA.currentValue} 15 times, but if the object does not exists, it stops with error "TypeError: Cannot read property 'currentValue' of undefined".
Is there some way to make this more smart? :slight_smile:
Thanks!

What other JSONata expression did you wish to join?
And what format should they be joined?

$sum(payload.currentPositions.DCA.totalCost)
$sum(payload.currentPositions.DCA.currentValue)
$sum(payload.currentPositions.PAIRS.totalCost)
$sum(payload.currentPositions.PAIRS.currentValue)

what format, comma seperated or json etc?

In Json if that would be possible :slight_smile:

```

{"key1": $sum(payload.currentPositions.DCA[].totalCost),
"key2": $sum(payload.currentPositions.DCA[].currentValue),
"key3": $sum(payload.currentPositions.PAIRS[].totalCost),
"key4": $sum(payload.currentPositions.PAIRS[].currentValue) }

```
notice backticks , they present code in easy form to copy, and prevent forum corrupting code. Please remember to use these in future posting, to make life easier

Thanks @E1cid This works perfectly :slight_smile:

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.