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

标签 javascript json object github github-api

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

我正在使用的实际数据来自 Github API。对于此示例,我需要所有要点的文件名。

[
  {
    "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 等自动成员,仅返回在对象上手动定义的成员。

关于Javascript:如果我不知道对象的键,如何访问嵌套对象中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23276068/

相关文章:

javascript - Rails 4 : how to use $(document). ready() 与 turbo-links

javascript - Scrapy-splash - 会溅起 :go(url) in lua_script perform GET request again?

javascript - 指向 JSON blob 中的不同值以放入数组

javascript - 既然我无法观察到,一个简单的 JS 对象怎么可能包含虚假属性?

java - 术语 "length"和 "size"之间是否存在技术差异(当然是在编程中)?

javascript - 多次对对象数组进行排序导致浏览器控制台出现奇怪的错误 | Javascript

javascript - 是否可以使用 “HERE Maps API for JavaScript” 以可接受的性能渲染邮政编码边框?

IE9 回调上 JSON 的 jQuery AJAX 请求未定义

Java Json 解析器数组

javascript - 如何根据条件向数组添加项目