Underscore javascript _.each loop for nested array properties

Hi Javascript / underscore guru.

Suppose I get a json object from a server that has an anonymous array nested as one of its properties ... how would I scroll this array in the _.each underscore method?

This is my json object:

"onlineUsers": [ { "Id": "users/2", "Name": "Hamish", "LatestActivity": "2013-01-17T04:02:14.2113433Z", "LatestHeartbeat": "2013-01-17T04:02:14.2113433Z" }, { "Id": "users/3", "Name": "Ken", "LatestActivity": "2013-01-17T03:45:20.066Z", "LatestHeartbeat": "2013-01-17T04:04:34.711Z" } ] 

How do I change this function to print names?

 _.each(onlineUsers, function(user){log(user.name);}); 

This prints the actual collection of nested objects, obviously because they are elements in a nested array of online users ... not sure how to get to this array before the loop if it is anonymously passed ...

Thanks Hamish.

+4
source share
2 answers

The JSON that you get from the server is invalid JSON. An array needs a property name, for example:

 onlineUsers = { names: [{name : "Joe"}, {name : "bloggs"}]} 

Then you can do this:

 _.each(onlineUsers.names, function(user){log(user.name);}); 
+14
source

An anonymous array inside an object is not valid json, so you cannot parse it.

either give the array a name or delete the external object.

+2
source

All Articles