views:

108

answers:

2

I'm using JQuery to get city data from geonames. My problem is when I want to extract the value for sub-array items when using the JQuery map function.

In this example, if I want to get the Wikipedia link, how could I do this?

I tried: wikipedia: item.alternateNames.lang['link']

but didn't expect it would really work. Does anyone know who I can extract the sub array items?

Here are the bits of code:

JSON RESULT

"geonames": [{
"alternateNames": [
  {
    "name": "Rancho Cucamonga",
    "lang": "en"
  },
  {
    "name": "91739",
    "lang": "post"
  },
  {
    "name": "http://en.wikipedia.org/wiki/Rancho_Cucamonga%2C_California",
    "lang": "link"
  }

],
adminCode2": "071",
"countryName": "United States",
"adminCode1": "CA",
"fclName": "city, village,...",
"elevation": 368,
"score": 0.9999999403953552,
"countryCode": "US",
"lng": -117.5931084,
"adminName2": "San Bernardino County",
"adminName3": "",
"fcodeName": "populated place",

JQuery:

$("#city").autocomplete({
        source: function(request, response) {
            $.ajax({
                url: "http://ws.geonames.org/searchJSON",
                dataType: "jsonp",
                data: {
                    featureClass: "P",
                    style: "full",
                    maxRows: 12,
                    name_startsWith: request.term
                },
                success: function(data) {

                    response($.map(data.geonames, function(item) {
                        return {
                            label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
                            value: item.name,
                            latitude: item.lat,
                            longitude: item.lng,

                            // problem here: how to get the value for the alternateNames.lang where lang = link
                            wikipedia: item.alternateNames.lang['link']

                        }
                    }))
                }
            })
        },
A: 

Your alternateNames is an array of objects, so you would have to use an index to retrieve an object from the array. Once you have the object you can retrieve the "lang" field:

item.alternateNames[2].lang

that should return you "link". This is assuming that item is the proper parent object of alternateNames.

stjowa
+1  A: 

Try...

wikipedia: item.alternateNames[2].name

But if you wanted to search them...

var name;
$.each( item.alternateNames, function(){
  if ( this.lang == 'link' ) {
    name = this.name;
    return false;
  }
});
BBonifield
Thanks very much this worked perfectly. Each entry might have several different alternateNames so I needed to find just the one with they key link.
Frank
Yeah, I imagined as much. Glad it worked.
BBonifield