Hello all,
I'm new to Node-RED and have been struggling with using JSONata to set nested object properties with the Change Node.
I have the following scenario where I need to access a particular property's value in a nested object, but where I don't know the name one of the parent properties.
I can get the property name using $keys(object)
however I then need to use the output of this as part of the dot notation to access the required property. A possible added complication is a hyphen in the unknown property name.
Despite some extensive research I just can't work out the correct syntax to achieve this.
Example object (where the property name "device-0001" is unknown in advance):
{
"device-0001": {
"name1": "value 1",
"name2": "value 2"
}
}
I can get the unknown property name with $keys(object)
$keys($.payload)[0]
which returns "device-0001"
However, if I use this as part of the dot notation
$.payload.$keys($.payload)[0].name1
then I get undefined
returned.
Although I do have two work arounds
- Save the object to the flow context first
$flowContext("devices." & $keys($flowContext("devices"))[0] & ".name1")
- Use a function node and JS
msg.payload = msg.payload[Object.keys(msg.payload)[0]].name1;
return msg;
I don't want to have to change several existing change nodes to functions nodes if possible and would prefer not to use the flow context. I also feel it should just be matter of using the correct syntax.
Any advice would be appreciated.
Regards
Simon
(Node-RED: v3.0.2)
(Node.js: v18.2.1)