How do i insert a variable in a function - in the string

In the function node I have a line that looks like this:

msg.payload.Rad1W = msg.payload.data.devices_status.ec62608de1cc["switch:0"].apower

Now... I would like to use the variables from the sub flow to replace the places 'ec62608de1cc' & '["switch:0"].'
How do insert the variables into those places so It can look something like this:
msg.payload.Rad1W = msg.payload.data.devices_status.Variable1Variable2.apower

const id = env.get('id') // e.g. ec62608de1cc
const prop = env.get('prop') // e.g. switch:0
msg.payload.Rad1W = msg.payload.data.devices_status[id][prop].apower
return msg

NOTE: I would recommend you break this down and add null/undefined guards e.g

const id = env.get('id') // e.g. ec62608de1cc
if (!id) {
    node.error('id is not set')
    return null
}
const prop = env.get('prop') // e.g. switch:0
if (!prop) {
    node.error('prop is not set')
    return null
}
const stat = msg.payload?.data?.devices_status?.[id]
if (!stat) {
    node.error('device status for id "' + id + '" was not found in the msg')
    return null
}
const statProp = stat[prop]
if (!statProp) {
    node.error('device status property "' + prop + '" for id "' + id + '" was not found in the msg')
    return null
}

msg.payload.Rad1W = statProp.apower
return msg

↑ 100% untested - but should get you close ↑

Awesome, with some modifications it did exactly what I needed!

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