javascriptobjectwikimedia

javascript select object key that changes


I am using the mediaWiki API to get a random article like:

https://en.wikipedia.org/w/api.php?action=query&generator=random&grnnamespace=0&format=json&grnlimit=1

An example response:

{
  "batchcomplete": "",
  "continue": {
  "grncontinue": "0.630140535217|0.63014105781|6813083|0",
  "continue": "grncontinue||"
  },
  "query": {
    "pages": {
     "2374863": {
       "pageid": 2374863,
       "ns": 0,
       "title": "Khvalynsk culture"
     }
    }
  }
}

When I turn it to a javascript object I get this:

query: {
        pages: {
            31676967: { // <-- changes each request
                pageid: 31676967, // <-- changes each request
                ns: 0,
                title: "HP Neoview"
            }
        }
    }

The key and the value I marked with <-- change every time I fetch. How can I get the key marked with <-- OR the value marked with <--. I can't select it like this:

query.pages.31676967.pageid

because the number changes. I've tried this:

query.pages[0].pageid

but that just returns undefined. Anyone know how I can do it?


Solution

  • If there is always only one page in the pages object, you can get it's value using Object.values method:

    let query = {
        pages: {
            '31676967': {
                pageid: 31676967,
                ns: 0,
                title: "HP Neoview"
            }
        }
    };
    
    let id = Object.values(query.pages)[0].pageid;
    
    console.log(id);