Access a payload property by using a string variable

Premise
My question is related to this Q&A as my problem is similar. I have a msg.payload which has several properties (as a matter of facts arrays, but this is not meaningful for the question) whose name is section_x where x is an integer which ranges fro 1 to at most 5 (I do not know a priori its value as it is determined by the action of several flows on the payload). I have to access one of these properties indexed by an integer i producer by another flow. I tried the following code following the cited Q&A

var v = [];
v = msg.payload.`section_${i}`; 
return msg;

but I did not succeed as the code does not compile. Now the questions:

  1. Can I access a payload property by using a similar expression? If yes, how?
  2. Where can I find examples of uses of the code as the one shown by Steve-Mcl in the Q&A cited above?

I don't know if you code is the correct way (without a good think about it :stuck_out_tongue: )... but I do know that you have to return the contents of v back to msg.payload before the return msg

msg.payload = v;

1 Like

Use RED.util.getObjectProperty

See similar thread here : Alternatives to eval() - #2 by Steve-Mcl

in your case...

var i = 1; // <<get from somewhere else. Hard coded to 1 for demo purposes
var varName = `section_${i}`
var v = RED.util.getObjectProperty(msg.payload, varName); 
1 Like

[ ] notation should work.

let i = "1";
msg.payload = msg.payload[`section_${i}`]; 
return msg;
1 Like

Wonderful, I tried it and it worked perfectly. Thank you, Steve.

I also tried your solutions and it works perfectly too: I decided to chose Steve's solution only since it suits better in my current project. However, I'll use yours in other occasions. Thank you, E1cid