Add an element on the go based on the value of msg.payload

Hi!
Apologies in advance, this may sound a simple question.

I would like to now how to create an element of msg.payload (or better, global.payload) based on the value of msg.payload.

In other words: I am receiving a msg.payload which is a number: "1". I want to store the state "True" in global.payload.1.

I can do it by hand, but I thought it could be more elegant if it was a function, but javascript is a spice I still don't master well.

My wrong flow (super basic)
flows.json (814 Bytes)

I would highly recommend to go through the documentation and how to work with messages. The videos in that document should help.

Thanks.
I've seen, reviewed and looked more into the topic, and partially succeded in what I want to do.

if I send the number 3 to this function (takjen from this helpful post)

let num = msg.payload;

msg.payload = {
    Element1: num,
    Element2: "Two",
    Element3: "Three"
}
msg.payload[msg.payload.Element1] = false;

return msg;

I end up creating a msg.payload.3 set to false.

Sadly I ended up stopping in the next problem: since I want to store this values in a global object, I've previously created three global variables that I want to update.

I create them using a change node, that I inject before testing the function:

Then I edited my code in the function: I want to update one of those variables based on the number passing throught the function:

let num = msg.payload;

msg.payload = {
    Element1: num,
    Element2: "Two",
    Element3: "Three"
}
msg.payload[msg.payload.Element1] = false;

global.meridiana[msg.payload.Element1] = false;

return msg;

This gives me an error: "TypeError: Cannot set property '3' of undefined"

Why is global.meridiana["3"] undefined since I previously declared it in the change node?


Why I have msg.payload assigned to 3 and not payload.3 = false from this function here?

let num = msg.payload;

msg.payload[num] = false;

return msg;

Sorry for the many questions: hoping in some help

Thanks in advance.
flows (1).json (1.9 KB)

There are easier ways to achieve it, but yes ... this works.
Have you tried

msg.payload[num] = false;

Did you read the documentation regarding context storage? If not - I'd like to strongly recommend to do it.

let num = msg.payload;
    console.log(typeof(msg.payload));  // check typeof msg.payload
msg.payload[num] = false;
    console.log(typeof(msg.payload));  // did you change it to another type?
return msg;

That's Javascript! I agree, it could be nicer & throw an error...

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