Trying to summate array

I have the following payload and I am trying to summate all the used: items

My code is:

var total=0;
var i=0;

for (i=0; i< msg.payload.ScannedCount; i++) {

total = total + msg.payload.Items[i].used;

msg.payload = total;
return msg;

But I keep getting 0?

The length on an array in JavaScript is accessed via .length not .ScannedCount

There is also no Items property in a JavaScript array.

msg.payload[i].used is how you would access the used property in the array element object.

Reference: Array - JavaScript | MDN

You can use the Array.reduce() function. Something like this.

msg.payload = msg.payload.reduce( accumulate, 0)
return msg;

// add this value to the total
function accumulate(total, thisOne) {
    return total + thisOne.used

See JavaScript Array reduce() Method

You can do this in a change node to, using JSONata. Feed your array into the change node to see the result.



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