0

I am toying around with the wiki API and trying to have an array of links from a given article returned. This is the kind of JSON i am working with:

{
  "continue": {
    "plcontinue": "22989|0|2007_Rugby_World_Cup",
    "continue": "||"
  },
  "query": {
    "normalized": [
      {
        "from": "paris",
        "to": "Paris"
      }
    ],
    "pages": {
      "22989": {
        "pageid": 22989,
        "ns": 0,
        "title": "Paris",
        "links": [
          {
            "ns": 0,
            "title": ", Île-de-France, Seine, Kingdom of France"
          },

As you can see I need to know the pageId for me to access the links array that I need. I tried extracting it from the plcontinue value and then have it inserted later in my code, but it returns an undefined.

This is my API request:

$.ajax({
        url: "https://en.wikipedia.org/w/api.php?action=query&titles=" + searchTerm + "&pllimit=50&prop=links&format=json",
        method: "GET",
        dataType: "jsonp" //allow CORS
    }).then(function (data) {
        var plcontinueArray = data.continue.plcontinue.split("|")
        var pageId = plcontinueArray[0];
        var links = data.query.pages.pageId.links;

How do i access the array of links when i do not know the pageId before making the request?

Leth
  • 1,033
  • 3
  • 15
  • 40

3 Answers3

2

In the same way that you use dot notation to access the data in an object, you can also use an index like method to access keys of an object.

For example:

var obj = { foo: "bar", spam: "eggs" };
var value1 = obj.foo; // value1 = "bar"
var keyName = "spam";
var value2 = obj[keyName]; // value12 = "eggs"

So for your example, you would do something like this -

...
var pageId = plcontinueArray[0];
var links = data.query.pages[pageId].links;
Lix
  • 47,311
  • 12
  • 103
  • 131
0

You are accessing the pageId incorrectly -

Change this line - var links = data.query.pages.pageId.links; to var links = data.query.pages[pageId].links;

Ashvin777
  • 1,446
  • 13
  • 19
0

You could just loop through the pages object with a for ... in loop. Something like this:

...

then(function (data) {
    for(var pageId in data.query.pages) {
       if (data.query.pages.hasOwnProperty(pageId)) {
            console.log(data.query.pages[pageId].links);
       }
    }
});

Hope it helps.

malifa
  • 8,025
  • 2
  • 42
  • 57