Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

underscore javascript _.each loop for properties nested array

Hi Javascript/underscore gurus..

Lets say I receive a json object from the server which has an anonymous array nested as one of its properties... how would i loop through that array in an underscore _.each 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 would I modify this function to print out the names?

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

This is printing out the actual collection of nested objects, obviously because they are elements in the nested array of onlineUsers... not sure how to get to that array to loop if it is anonymously passed in...

Thanks, Hamish.

like image 489
HCdev Avatar asked Dec 05 '22 12:12

HCdev


1 Answers

The JSON you are receiving from the server is invalid JSON. The array needs a property name, eg:

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

Then you could do this:

_.each(onlineUsers.names, function(user){log(user.name);});
like image 70
Frank Radocaj Avatar answered Dec 28 '22 09:12

Frank Radocaj