Trying to summate array

Hello
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.

$sum($$.payload.used)

[{"id":"8b46158f.df50e8","type":"inject","z":"b779de97.b1b46","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"[{\"used\":2},{\"used\":4}]","payloadType":"json","x":460,"y":3820,"wires":[["3b5365c7.3e3092"]]},{"id":"3b5365c7.3e3092","type":"change","z":"b779de97.b1b46","name":"","rules":[{"t":"set","p":"payload","pt":"msg","to":"$sum($$.payload.used)","tot":"jsonata"}],"action":"","property":"","from":"","to":"","reg":false,"x":710,"y":3820,"wires":[["a76897c9.a113f8"]]},{"id":"a76897c9.a113f8","type":"debug","z":"b779de97.b1b46","name":"","active":true,"console":"false","complete":"false","x":899,"y":3740,"wires":[]}]

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