Dynamically select msg.payload key element

I have looked around but found nothing that answer my situation.

I want to setup a global variable. The value of the variable will come from the msg.payload BUT, the element name (key) will be dynamically build like so:

global.set("ConnectServerUrl",msg.payload.ConnectServerUrl <-DEV,-TEST,-PROD>)

The -DEV or -TEST or -PROD is from another global variable name global.environment.

Welcoome to the forum @hameljc

Try something like

global.set("ConnectServerUrl",`${msg.payload.ConnectServerUrl} ${global.get("environment")}`)

That is assuming that the global variable is "environment" not global.environment. It would probably not be a good idea to have a global variable called global, that would surely be confusing.

The backtick syntax is called template literals, see JavaScript Template Literals

Thanks for your reply but the concatenation doesn't need to be with the value of msg.payload.ConnectServerUrl but rather to define/name the element/key ConnectServerUrl like so:

The -DEV or -TEST or -PROD will come from another global variable name environment.

I am looking for a way to dynamically set the name of the key in the msg.payload

If i understand correctly, try

const key = "ConnectServerUrl-" + (global.get("environment") || "default");
global.set("ConnectServerUrl", msg.payload[key]);

If that isn't it then give us some examples of actual values in the globals and msg.payload and tell us what you want to happen.

Thank you E1cid, exactly what I needed :smiley:

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