如何获取MediaWiki API返回对象中动态变化的pages键对应数据?
query.pages Response I'm using the MediaWiki API to fetch random Wikipedia articles. Here's my request example:
https://en.wikipedia.org/w/api.php?action=query&generator=random&grnnamespace=0&format=json&grnlimit=1The sample JSON response looks like this:
{ "batchcomplete": "", "continue": { "grncontinue": "0.630140535217|0.63014105781|6813083|0", "continue": "grncontinue||" }, "query": { "pages": { "2374863": { "pageid": 2374863, "ns": 0, "title": "Khvalynsk culture" } } } }After converting this to a JavaScript object, the key under
query.pagesis a dynamically changing number. How can I select the object corresponding to this dynamic key?
Great question—this is a common gotcha with APIs that use dynamic keys instead of arrays for single-item collections. Since you're setting grnlimit=1, we know there will only be one entry in the pages object, which simplifies things. Here are a few straightforward methods to access it:
Method 1: Use Object.values() for direct access
Object.values() extracts all the values from an object into an array. Since there's only one page, we can grab the first (and only) item in that array:
// Assume `apiResponse` is your parsed JavaScript object from the API const pageObject = Object.values(apiResponse.query.pages)[0]; console.log(pageObject.title); // Outputs: "Khvalynsk culture"
Method 2: Use Object.keys() if you need the page ID too
If you want to capture the dynamic page ID (the numeric key) along with the page data, use Object.keys() to get the key first:
const pageKeys = Object.keys(apiResponse.query.pages); const pageId = pageKeys[0]; // Gets "2374863" from the sample response const pageObject = apiResponse.query.pages[pageId]; console.log(`Page ID: ${pageId}, Title: ${pageObject.title}`); // Outputs: "Page ID: 2374863, Title: Khvalynsk culture"
Method 3: Destructuring with Object.entries() for conciseness
For a more modern, concise approach, combine Object.entries() (which returns key-value pairs as arrays) with array destructuring:
const { query: { pages } } = apiResponse; // Grab the first key-value pair from the pages object const [pageId, pageObject] = Object.entries(pages)[0]; console.log(pageObject.title); // Outputs: "Khvalynsk culture"
Bonus: Handling multiple pages
If you ever increase grnlimit to fetch more than one random article, you can loop through the results easily with any of these methods. For example:
// Loop through all pages using Object.values() Object.values(apiResponse.query.pages).forEach(page => { console.log(`Title: ${page.title}, Page ID: ${page.pageid}`); });
内容的提问来源于stack exchange,提问作者user6514554

