如果我有一个从 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/