How do I set an array to a variable

For example in the given array; (array is updated with different value every sec)
[93,30,9]

I would like to indicate that 93 is humidity, 30 is temperature, 9 is x in JSON format. [which look something like this ( "humidity": 93, "temperature": 30, "x": 9 ) ]

Any idea what the code is like in the function node?
var humidity;
msg.payload = msg.payload.humidity;
return msg;

Assuming the array if passed in the msg.

msg.payload = {"humidity": msg[0], 
               "temperature": msg[1], 
               "x": msg[2]
};
return msg;
2 Likes

This error occurred when I input your function code

alright got it working thanks !!

msg.payload = {"humidity": msg.payload[0],
"temperature": msg.payload[1],
"vibration": msg.payload[2]
};
return msg;

For future reference, since they do not contain any special characters, you do not need to put the attribute names humidity, temperature or vibration in quotes.

1 Like

does that mean if i remove the quote, it will still work normally?

Yes
x = {name: 1}
is identical to
x = {"name": 1}
If, however the attribute had unusual characters, a minus sign for example, or a space, or starts with a number, then you would need the quotes
x = {"name-1": 1}
as otherwise it will try to interpret the - as a minus sign.
If you were creating a JSON string though (as opposed to a javascript object) then you would need
string = '{"name":1}'
in order to build a valid JSON string.

1 Like

alright cool thanks for the info!

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