How to extract a property with a change node

How do I extract the property payload.common.states["2"] from an object, referring to the val .

{"common":{"states":{"0":"idle","2":"water leak detected"}},"val":2}

A function node with the following code is working:

msg.payload = msg.payload.common.states[msg.payload.val];
return msg;

A Change Node with JSONATA does not work.

is payload.val a string then I get always the object:

is payload.val a number I get undefined.

Is there a possibility to use a change node to set the payload to the common.states property of payload.val?

Try $lookup(payload.common.states, $string($lookup(payload, "val")))

1 Like

Ok - $lookup is working. Thank you - the second part can be shortened.

 $lookup(payload.common.states, $string(payload.val))

I was a little bit surprised that there is not a simpler solution.

You do not need to call JSONata to do this, just
set msg. payload
to msg. payload.common.states[msg.payload.val]
e.g.

[{"id":"49546b30e8e5fb6e","type":"change","z":"452103ea51141731","name":"","rules":[{"t":"set","p":"payload","pt":"msg","to":"payload.common.states[msg.payload.val]","tot":"msg"}],"action":"","property":"","from":"","to":"","reg":false,"x":320,"y":3440,"wires":[["b79c522c6df54913"]]},{"id":"01baa9592fe584f0","type":"inject","z":"452103ea51141731","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"{\"common\":{\"states\":{\"0\":\"idle\",\"2\":\"leak\"}},\"val\":2}","payloadType":"json","x":150,"y":3440,"wires":[["49546b30e8e5fb6e"]]},{"id":"b79c522c6df54913","type":"debug","z":"452103ea51141731","name":"debug 110","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":530,"y":3380,"wires":[]}]

Works if val is a string or number.

1 Like

Many - many thanks. Great solution!!!

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