Variable as message property

Hello folks,

I am trying to compare a number of message properties in a function node and would like to do this with variables rather than repeating each object path. The trouble I am having is that I can't work out how to build the variables into the object path.

What I have so far is:

//variables
var current = "v_hallightgrp";
var target = "c_lightnight";

//compare brightness
if (msg.payload.+current+.brightness !== msg.payload.+target+.brightness) {

This is throwing an error. I know putting it in quotes isn't the answer as that converts the object paths to strings. Thanks in advance for your help!

Edit:
Strings defined correctly for variables (thanks Johannes)

You can use a variable as an object key by putting it in square brackets. For example

const key = "test";
msg.payload = msg.payload[key];
return msg;

Would return msg.payload.test as the msg.payload.

Johannes

Edit:

Also

Where did you define v_hallightgrp and c_lightnight or did you mean them to be strings? Because the way you wrote it above without " before and after is trying to reference a variable of the name v_hallightgrp that in itself would have to be defined somewhere.

That should be
if (msg.payload[current].brightness !== msg.payload[target].brightness) {
The dot syntax is a shorthand for the square bracket notation, so the above line is actually a shorthand way of writing
if (msg["payload"][current]["brightness"] !== ....

Thank you Johannes and Colin. I've tested and got it working now. Much obliged.

Joannes, well spotted, I meant them to be strings. I've edited the OP so as to help others in the future.

1 Like

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