Declaring array of objects in payload

Hello. I'm trying to declare an array of objects into my msg.payload using a JavaScript node.
I declare my array as such:

        msg.payload = {
            DeviceID :  '0',
            Sensors :  []
        }

And the Sensors array is suposed to contain objects that look like this:

{
     SensorID : 'NULL',
     Value : 0
}

However, I'm having trouble inserting a new instance of an object into Sensors. For example: If I try to insert a value after the array declaration, ex: msg.payload.Sensors[index].Value = myValue, I get an error telling me that the array Sensors is undeclared, and that I can't set it's value.
How would i go about declaring the Sensors array properly in order to insert new values at a given index?

I don't think you can assign values to payload.Sensors[n] until that array element exists.
You need to push the object onto the array.

msg.payload = {
    DeviceID: '0',
    Sensors: []
}
const obj = {"SensorID": 42, "Value": 98}
msg.payload.Sensors.push(obj)
1 Like

Or you would have to declare the Sensors index as an object first.
e.g.

msg.payload.Sensors[index] = {}; // make sure outside loop or will over write index value.
msg.payload.Sensors[index].value = 0;

Or

msg.payload.Sensors[index] = {SensorID: null, Value: 0};

Thank you. This worked for me.

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