Finding value in array of JSON Objects

Hello - Please advise how to find a specifc value for "sw-a" (see below), and return the value in "zone". I am unable to change the format of the array without causing other issues. I've tried several variations of the following:

var lookupMatch = arrSB.find(el => input === el.in);

where arrSB =

[
{"id":0,"zone":1,"config":1,"sw-a":452,"sw-b":0,"sw-c":0},
{"id":1,"zone":1,"config":1,"sw-a":454,"sw-b":0,"sw-c":0},
{"id":2,"zone":1,"config":1,"sw-a":448,"sw-b":0,"sw-c":0},
null,
{"id":4,"zone":2,"config":1,"sw-a":464,"sw-b":0,"sw-c":0}
]

Try this .. although i dont think you should have an element null in your array because when find()
loops through the data and reaches null it will fail.

[{"id":"8d11464692374d8f","type":"inject","z":"54efb553244c241f","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"452","payloadType":"num","x":290,"y":1520,"wires":[["8b73380ec5b740bb"]]},{"id":"8b73380ec5b740bb","type":"function","z":"54efb553244c241f","name":"function","func":"let input = msg.payload\n\nlet arrSB = [\n    { \"id\": 0, \"zone\": 1, \"config\": 1, \"sw-a\": 452, \"sw-b\": 0, \"sw-c\": 0 },\n    { \"id\": 1, \"zone\": 1, \"config\": 1, \"sw-a\": 454, \"sw-b\": 0, \"sw-c\": 0 },\n    { \"id\": 2, \"zone\": 1, \"config\": 1, \"sw-a\": 448, \"sw-b\": 0, \"sw-c\": 0 },\n    { \"id\": 4, \"zone\": 2, \"config\": 1, \"sw-a\": 464, \"sw-b\": 0, \"sw-c\": 0 }\n];\n\nmsg.payload = arrSB.find(el => el[\"sw-a\"] === input)\n\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":490,"y":1580,"wires":[["06213bc550d2fc17"]]},{"id":"06213bc550d2fc17","type":"debug","z":"54efb553244c241f","name":"debug","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":750,"y":1580,"wires":[]},{"id":"a2fa86fded769230","type":"inject","z":"54efb553244c241f","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"464","payloadType":"num","x":290,"y":1620,"wires":[["8b73380ec5b740bb"]]}]

ps. you could do a check and skip that null element
msg.payload = arrSB.find(el => (el === null) ? false : (el["sw-a"] === input))
but .. what is it doing there in your data ? :wink:

Thank you. I was just getting ready to post a solution to filter out the null data, but your solution is far simplier. I'm not exactly sure how the null data is getting into it. Modifing the source of the data is another can of worms.

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