json to JS object - extracting an object from a sub-array object by selecting with a field...

772 views
Skip to first unread message

JR01

unread,
Aug 13, 2016, 1:36:35 PM8/13/16
to Node-RED
Hi, in a function node, I apply the js below to an incoming json array.

var a = JSON.parse(msg.payload);
var b = a.Sensors ;
msg.payload = b;
return msg;

It then returns the sub-array below (from the Sensors object). Apart from a function a.Sensors[1], how can I extract a value by pointing in a filter or some sort of select command of "Relay2" ?

[ { "TaskName": "Switch", "Relay1": 0 }, { "TaskName": "Switch", "Relay2": 0 }, { "TaskName": "Switch", "Relay3": 0 }, { "TaskName": "Switch", "Relay4": 0 }, { "TaskName": "Switch", "Relay5": 0 }, { "TaskName": "System", "Uptime": 290 }, { "TaskName": "Water", "Muni": 0, "Total": 0, "Time": 0 }, { "TaskName": "Water", "Bore": 0, "Total": 0, "Time": 0 }, { "TaskName": "Air", "Temperature": 16.5, "Humidity": 26 } ]

(Sorry, I know this is not a node red question, but a java script issue, I have asked the question on stack overflow, but 2 days later no-one has answered yet. Maybe to basic to answer.... I have searched the forum, but from the examples I could not get it to work yet... sorry for asking !)

Nicholas O'Leary

unread,
Aug 13, 2016, 7:12:41 PM8/13/16
to Node-RED Mailing List
If I understand correctly, you want to find the element in that array which has a property of Relay2, without relying on the fact it happens to be the second element in this instance.

One way to do it would be to first filter that array to only elements that have the 'Relay2' property.

    var filtered = a.Sensors.filter(function(element) { return element.hasOwnProperty('Relay2'); });


'filtered' is now an array of matching elements. You can then do with them whatever you want... if there's only every one, you can safely use filtered[0].

Nick


--
http://nodered.org
 
Join us on Slack to continue the conversation: http://nodered.org/slack
---
You received this message because you are subscribed to the Google Groups "Node-RED" group.
To unsubscribe from this group and stop receiving emails from it, send an email to node-red+unsubscribe@googlegroups.com.
To post to this group, send email to node...@googlegroups.com.
Visit this group at https://groups.google.com/group/node-red.
For more options, visit https://groups.google.com/d/optout.

JR01

unread,
Aug 14, 2016, 2:01:55 AM8/14/16
to Node-RED
Thank you Nick!
Reply all
Reply to author
Forward
0 new messages