繁体   English   中英

Javascript:如果我不知道对象的密钥,如何访问嵌套对象中的值?

[英]Javascript: How do I access values in nested objects if I don’t know the object’s key?

如果我有一个Javascript对象,从JSON解析,嵌套三个深,我不知道中间的密钥,如何访问它及其内容?

我正在使用的实际数据来自Github API。 对于这个例子,我想要所有gist的文件名。

[
  {
    "url": "https://api.github.com/gists/11164200",
    "forks_url": "https://api.github.com/gists/11164200/forks",
    "commits_url": "https://api.github.com/gists/11164200/commits",
    "id": "11164200",
    "git_pull_url": "https://gist.github.com/11164200.git",
    "git_push_url": "https://gist.github.com/11164200.git",
    "html_url": "https://gist.github.com/11164200",
    "files": {
      "testing.md": {
        "filename": "testing.md",
        "type": "text/plain",
        "language": "Markdown",
        "raw_url": "https://gist.githubusercontent.com/omphalosskeptic/11164200/raw/3582779a4925ea514382cedb7d077d00c231f3eb/testing.md",
        "size": 4254
      }
    }, // [ ... continues]

我的Javascript技能很简陋。 通常情况下,我可以通过足够的研究找到我正在寻找的东西但不是这次。 最初我预计它会是这样的: responseObj[0].files[0].filename

如果可能的话,我想保留这个简单的Javascript。

谢谢!

根据您发布的示例, files属性不是数组,因此索引器无法访问。 在这种情况下,您将使用for-in循环而不是常规for循环。

for(var p in responseObj[0].files) {                 
  if ( responseObj[0].files.hasOwnProperty (p) ) {   
    p; // p is your unknown property name
    responseObj[0].files[p]; // is the object which you can use to access 
                             // its own properties (filename, type, etc)           
  }                                                                                                           
}

hasOwnProperty检查将跳过像toString这样的自动成员,并仅返回在对象上手动定义的成员。

如果你想迭代它们,做一些类似的事情

for (var fileID in responseObj[0].files) {
    var file = responseObj[0].files[fileID];
    var filename = file.filename;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM