簡體   English   中英

使用香草JavaScript訪問嵌套在JSON對象中的具有已知名稱的屬性的值

[英]Accessing the value of a property with a known name that is nested in a JSON object with vanilla JavaScript

感謝您抽出寶貴時間閱讀我的問題! 我是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屬性的值?

非常感謝您的幫助!

如果只有一個鍵,則可以使用data.query.pages Object.keys獲得第一個元素。

 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); 

如果對象始終只有一個屬性名稱,請獲取屬性名稱並通過方括號表示法訪問該屬性:

var key = // see https://stackoverflow.com/q/6765864/218196
query.pages[key].fullurl

如果有多個屬性,請遍歷對象,例如,通過for...in 請參閱訪問/處理(嵌套)對象,數組或JSON

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM