感谢您花时间阅读我的问题!我是 JavaScript 新手,一直无法找到以下问题的解决方案:
如何访问嵌套在名称动态更改的属性下的 JSON 对象中的属性值?
JSON 对象:
{
"batchcomplete": "",
"query": {
"normalized": [
{
"from": "Theodore_Rubin",
"to": "Theodore Rubin"
}
],
"pages": {
"11820415": {
"pageid": 11820415,
"ns": 0,
"title": "Theodore Rubin",
"contentmodel": "wikitext",
"pagelanguage": "en",
"pagelanguagehtmlcode": "en",
"pagelanguagedir": "ltr",
"touched": "2016-02-12T17:34:52Z",
"lastrevid": 138813300,
"length": 34,
"redirect": "",
"new": "",
"fullurl": "https://en.wikipedia.org/wiki/Theodore_Rubin",
"editurl": "https://en.wikipedia.org/w/index.php?title=Theodore_Rubin&action=edit",
"canonicalurl": "https://en.wikipedia.org/wiki/Theodore_Rubin"
}
}
}
}
我正在尝试将属性 fullurl
的值分配给一个变量。据我了解,我可以使用括号和点符号的组合来访问 fullurl
,例如 query.pages["2123909"].fullurl
。问题在于属性名称 ["2123909"]
随着每个 JSON 请求的变化而变化。
如何在不知道嵌套属性名称的情况下访问 fullurl
属性的值?
非常感谢您的帮助!
最佳答案
如果只有一个键,则可以使用 Object.keys
获取第一个元素data.query.pages
。
var data = {
"batchcomplete": "",
"query": {
"normalized": [
{
"from": "Theodore_Rubin",
"to": "Theodore Rubin"
}
],
"pages": {
"11820415": {
"pageid": 11820415,
"ns": 0,
"title": "Theodore Rubin",
"contentmodel": "wikitext",
"pagelanguage": "en",
"pagelanguagehtmlcode": "en",
"pagelanguagedir": "ltr",
"touched": "2016-02-12T17:34:52Z",
"lastrevid": 138813300,
"length": 34,
"redirect": "",
"new": "",
"fullurl": "https://en.wikipedia.org/wiki/Theodore_Rubin",
"editurl": "https://en.wikipedia.org/w/index.php?title=Theodore_Rubin&action=edit",
"canonicalurl": "https://en.wikipedia.org/wiki/Theodore_Rubin"
}
}
}
};
console.log(data.query.pages[Object.keys(data.query.pages)[0]].fullurl);
关于javascript - 使用普通 JavaScript 访问嵌套在 JSON 对象中的已知名称的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40387992/