Как проверить, находится ли объект в json? - PullRequest
0 голосов
/ 21 ноября 2018

Я использую автозаполнение карт Google и извлекаю каждый объект в поле вроде этого:

$("#usp-custom-21").val(arrAddress.filter(x => x.types.includes("route"))[0].long_name);
$("#usp-custom-22").val(arrAddress.filter(x => x.types.includes("street_number"))[0].long_name);
$("#usp-custom-23").val(arrAddress.filter(x => x.types.includes("locality"))[0].long_name);
$("#usp-custom-8").attr("value", arrAddress.filter(x => x.types.includes("country"))[0].long_name);
$("#usp-custom-25").val(arrAddress.filter(x => x.types.includes("postal_code"))[0].long_name);

Но бывает, что иногда у нас нет некоторых или всех этих полей, и мыполучить эту ошибку:

Uncaught TypeError: Невозможно прочитать свойство 'long_name' из неопределенного

Я пытаюсь выполнить условие, проверив, есть эти поля или нет,и я попробовал обе проверки на наличие undefined или просто, если он там есть:

if(arrAddress.filter(x => x.types.includes("route"))[0] != "undefined") {
   $("#usp-custom-21").val(arrAddress.filter(x => x.types.includes("route"))[0].long_name);
}
if(arrAddress.filter(x => x.types.includes("street_number"))[0].long_name){
   $("#usp-custom-22").val(arrAddress.filter(x => x.types.includes("street_number"))[0].long_name);
}

Но я все еще получаю:

Uncaught TypeError: Невозможно прочитать свойство 'long_name' изundefined

И это относится к string long_name внутри if

Полный код:

  autocomplete.addListener('place_changed', function() {
    var place = autocomplete.getPlace();
    if (!place.geometry) {
      return;
    }
    if (place.geometry.viewport) {
      map.fitBounds(place.geometry.viewport);
    } else {
      map.setCenter(place.geometry.location);
    }
    marker.setPosition(place.geometry.location);
    currentLatitude = place.geometry.location.lat();
    currentLongitude = place.geometry.location.lng();
    var arrAddress = place.address_components;
    var Newlat = map.getCenter().lat();
    var NewLong = map.getCenter().lng();
    $("#usp-custom-19").val(parseInt(Newlat));
    $("#usp-custom-20").val(parseInt(NewLong));
    if(arrAddress.filter(x => x.types.includes("route"))[0] != "undefined") {
      $("#usp-custom-21").val(arrAddress.filter(x => x.types.includes("route"))[0].long_name);
    }
    if(arrAddress.filter(x => x.types.includes("street_number"))[0].long_name){
      $("#usp-custom-22").val(arrAddress.filter(x => x.types.includes("street_number"))[0].long_name);
    }
    if(arrAddress.filter(x => x.types.includes("locality"))[0].long_name) {
      $("#usp-custom-23").val(arrAddress.filter(x => x.types.includes("locality"))[0].long_name);
    }
    if(arrAddress.filter(x => x.types.includes("country"))[0].long_name) {
      $("#usp-custom-8").val(arrAddress.filter(x => x.types.includes("country"))[0].long_name);
    }
    if(arrAddress.filter(x => x.types.includes("postal_code"))[0].long_name) {
      $("#usp-custom-25").val(arrAddress.filter(x => x.types.includes("postal_code"))[0].long_name);
    }
    if(place.formatted_address) {
      $("#usp-custom-60").val(place.formatted_address);
    }
    $("#usp-custom-90").val(Newlat+","+NewLong);
    console.log(place.formatted_address);
  });

Ответы [ 2 ]

0 голосов
/ 21 ноября 2018

Вы пробовали это?

if(arrAddress.filter(x => x.types.includes("route"))[0].long_name != "undefined") {
   $("#usp-custom-21").val(arrAddress.filter(x => x.types.includes("route"))[0].long_name);
}

Вы также можете проверить наличие NaN или нулевых типов.Используйте typeof, чтобы определить тип при сбое:

console.log(typeof x.types.includes("route"))[0])

или

console.log(typeof x.types.includes("route"))[0].long_name)
0 голосов
/ 21 ноября 2018

Попробуйте это:

if(arrAddress.filter(x => x.types.includes("route"))[0] != undefined) {
   $("#usp-custom-21").val(arrAddress.filter(x => x.types.includes("route"))[0].long_name);
}
if(arrAddress.filter(x => x.types.includes("street_number"))[0] != undefined){
   $("#usp-custom-22").val(arrAddress.filter(x => x.types.includes("street_number"))[0].long_name);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...