Ignat Ospadov Ignat Ospadov - 1 month ago 6
Javascript Question

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

Thank you for taking the time to read my question! I am new to JavaScript and have been unable to find a solution to the following question:

How can I access the value of a property that is nested in a JSON object under a property whose name dynamically changes?

The JSON object:

{
"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"
}
}
}
}


I am trying to assign the value of the property
fullurl
to a variable. I understand that I can use a combination of bracket and dot notation to access the
fullurl
such as
query.pages["2123909"].fullurl
. The problem is that the property name
["2123909"]
changes with each JSON request.

How can I access the value of
fullurl
property without knowing the name of the property that it is nested in?

Thank you very much for your help!

Answer

If there is only one key, you could get the first element with Object.keys of 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);

Comments