用于属性嵌套数组的下划线 javascript _.each 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14371955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:28:02  来源:igfitidea点击:

underscore javascript _.each loop for properties nested array

javascriptjsonunderscore.js

提问by HCdev

Hi Javascript/underscore gurus..

嗨 Javascript/下划线大师..

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?

假设我从服务器收到一个 json 对象,它有一个嵌套的匿名数组作为其属性之一......我将如何在下划线 _.each 方法中遍历该数组?

This is my json object:

这是我的 json 对象:

  "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...

这是打印出嵌套对象的实际集合,显然是因为它们是 onlineUsers 嵌套数组中的元素……如果匿名传入,不确定如何进入该数组进行循环……

Thanks, Hamish.

谢谢,哈米什。

回答by Frank Radocaj

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

您从服务器收到的 JSON 是无效的 JSON。该数组需要一个属性名称,例如:

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

Then you could do this:

那么你可以这样做:

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

回答by Austin Greco

An anonymous array inside an object is not valid json, so you wouldn't be able to parse it.

对象内的匿名数组不是有效的 json,因此您将无法解析它。

either give the array a name or remove the outer object.

要么为数组命名,要么删除外部对象。