Карта JQuery и JSON - получение элементов подмассива - PullRequest
1 голос
/ 16 сентября 2010

Я использую JQuery для получения данных о городе из географических названий. Моя проблема - когда я хочу извлечь значение для элементов подмассива при использовании функции карты JQuery.

В этом примере, если я хочу получить ссылку на Википедию, как я могу это сделать?

Я пытался: Википедия: item.alternateNames.lang ['ссылка']

но не ожидал, что это действительно сработает. Кто-нибудь знает, кто мне может извлечь элементы подмассива?

Вот биты кода:

РЕЗУЛЬТАТ JSON

"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']

                        }
                    }))
                }
            })
        },

Ответы [ 3 ]

3 голосов
/ 16 сентября 2010

Try ...

wikipedia: item.alternateNames[2].name

Но если вы хотите найти их ...

var name;
$.each( item.alternateNames, function(){
  if ( this.lang == 'link' ) {
    name = this.name;
    return false;
  }
});
0 голосов
/ 26 сентября 2012

В той же аварии я нахожу следующее решение:

Вместо вызова подэлементов lang undo map, вы можете назначить только родительский элемент wikipedia: item.alternateNames.И после этого вы можете получить доступ к вложенным элементам из них в событии выбора автозаполнения.

Это мой пример:

$("#Customer_Name ").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '@Url.Action("LookupCustomers", "Customers")', type: "POST", dataType: "json",
                    data: { searchText: request.term, maxResults: 10 },
                    success: function (data) {

                            response($.map(data, function (item) {

                        //respose($.each(data, function (item

                            return {
                                label: item.Name,
                                value: item.Name,
                                id: item.Id,
                                phone: item.Phone,
                                addressStreet: item.AddressStreet,
                                addressBuilding: item.AddressBuilding,
                                addressHousing: item.AddressHousing,
                                addressFlat: item.AddressFlat,
                                metroStationId: item.MetroStationId,
                                metroStation: item.MetroStation  //trouble was here

                            }
                        }))
                    }
                })
            },
            select: function (event, ui) {
                document.getElementById("Customer_Id").value = ui.item.id;
                document.getElementById("Customer_Name").value = ui.item.value;
                document.getElementById("Customer_Phone").value = ui.item.phone;
                document.getElementById("Customer_AddressStreet").value = ui.item.addressStreet;
                document.getElementById("Customer_AddressBuilding").value = ui.item.addressBuilding;
                document.getElementById("Customer_AddressHousing").value = ui.item.addressHousing;
                document.getElementById("Customer_AddressFlat").value = ui.item.addressFlat;
                document.getElementById("Customer_MetroStationId").value = ui.item.metroStationId;
                document.getElementById("Customer_MetroStation_Name").value = ui.item.metroStation.Name;  //and, trouble was here
            }
        });
0 голосов
/ 16 сентября 2010

Ваш alternateNames является массивом объектов, поэтому вам придется использовать индекс для извлечения объекта из массива. Если у вас есть объект, вы можете получить поле «lang»:

item.alternateNames[2].lang

, который должен вернуть вам «ссылку». Это предполагает, что item является правильным родительским объектом для alternateNames.

...