How to check if an object has a string?

0

I have the following problem, I need to check if an object has a certain string, this object comes from the google places API autocomplete.

This is a return json, for example:

{
"address_components": [{
    "long_name": "1219",
    "short_name": "1219",
    "types": ["street_number"]
}, {
    "long_name": "Avenida Corrientes",
    "short_name": "Av. Corrientes",
    "types": ["route"]
}, {
    "long_name": "San Nicolas",
    "short_name": "San Nicolas",
    "types": ["sublocality_level_1", "sublocality", "political"]
}, {
    "long_name": "Comuna 1",
    "short_name": "Comuna 1",
    "types": ["administrative_area_level_2", "political"]
}, {
    "long_name": "Buenos Aires",
    "short_name": "CABA",
    "types": ["administrative_area_level_1", "political"]
}, {
    "long_name": "Argentina",
    "short_name": "AR",
    "types": ["country", "political"]
}, {
    "long_name": "C1043",
    "short_name": "C1043",
    "types": ["postal_code"]
}, {
    "long_name": "AAM",
    "short_name": "AAM",
    "types": ["postal_code_suffix"]
}],
"adr_address": "<span class=\"street-address\">Av. Corrientes 1219</span>, <span class=\"postal-code\">C1043AAM</span> <span class=\"locality\">CABA</span>, <span class=\"country-name\">Argentina</span>",
"formatted_address": "Av. Corrientes 1219, C1043AAM CABA, Argentina",
"geometry": {
    "location": {
        "lat": -34.6037445,
        "lng": -58.383988199999976
    },
    "viewport": {
        "south": -34.60514058029149,
        "west": -58.3853329302915,
        "north": -34.6024426197085,
        "east": -58.38263496970848
    }
},
"icon": "https://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png",
"id": "125f7a07fb81d10e98cec399869aaa694cb4b61f",
"name": "Av. Corrientes 1219",
"place_id": "ChIJC05_5cXKvJURhKX6uVXO7eE",
"reference": "CmRbAAAA5p8P3NP9ZMf2RjufMeNs8TZCrG4xe5ItjNYkKoYCcD8wpVG_bujknZM_8cj2k1e2Dtqg1bFjzxSkHTgH1o9MYIiBt1_bozOcgKbSXf95KJNttYd-2pg-E_iKxPH5eZHfEhAl0QPng-2n3Es9Q20B7c-ZGhTW6b2CtvBfBZuA_qUSLJvvngXGMA",
"scope": "GOOGLE",
"types": ["street_address"],
"url": "https://maps.google.com/?q=Av.+Corrientes+1219,+C1043AAM+CABA,+Argentina&ftid=0x95bccac5e57f4e0b:0xe1edce55b9faa584",
"utc_offset": -180,
"vicinity": "San Nicolas",
"html_attributions": []
}

What I need to do is check whether the "postal_code" or "postal_code_suffix" types exist in "address_components" .

>

What I did was go through the objects but I can not get the postal_code or postal_code_suffix without passing the position "manually".

var place = autocomplete.getPlace();
console.log(JSON.stringify(place));

for (var i = 0; i < place.address_components.length; i++) {
  for (var j = 0; j < place.address_components[i].types.length; j++) {
    var arrayTipos = [];                                                               
    arrayTipos.push(place.address_components[i].types[j]);
    var arrayValido = arrayTipos.indexOf('postal_code_suffix');

    if (arrayValido == 0) {
      var postalCode = place.address_components[6].long_name;
      var postalCodeSufix = place.address_components[7].long_name;
      var fullPostalCode = postalCodeSufix + postalCode;                                                       
      $('#codigoPostal').val(fullPostalCode);
    } else {
      $('#codigoPostal').val('');
    }
  }
}
    
asked by anonymous 06.11.2017 / 14:50

2 answers

1

You can use find to find objects that have postal_code or postal_code_suffix in the types array and use them to return the postal code.

Using the getPostalCode function of the snippet your code would look like this

var place = autocomplete.getPlace();
$('#codigoPostal').val(getPostalCode(place));

function getPostalCode(json) {
  var addrs = json.address_components
  var code = addrs.find(addr => addr.types.indexOf('postal_code') !== -1)
  var suffix = addrs.find(addr => addr.types.indexOf('postal_code_suffix') !== -1)
  if (!code || !suffix) {
    return ''
  }
  return code.long_name + suffix.long_name
}

var place = {
  "address_components": [{
    "long_name": "1219",
    "short_name": "1219",
    "types": ["street_number"]
  }, {
    "long_name": "Avenida Corrientes",
    "short_name": "Av. Corrientes",
    "types": ["route"]
  }, {
    "long_name": "San Nicolas",
    "short_name": "San Nicolas",
    "types": ["sublocality_level_1", "sublocality", "political"]
  }, {
    "long_name": "Comuna 1",
    "short_name": "Comuna 1",
    "types": ["administrative_area_level_2", "political"]
  }, {
    "long_name": "Buenos Aires",
    "short_name": "CABA",
    "types": ["administrative_area_level_1", "political"]
  }, {
    "long_name": "Argentina",
    "short_name": "AR",
    "types": ["country", "political"]
  }, {
    "long_name": "C1043",
    "short_name": "C1043",
    "types": ["postal_code"]
  }, {
    "long_name": "AAM",
    "short_name": "AAM",
    "types": ["postal_code_suffix"]
  }],
  "adr_address": "<span class=\"street-address\">Av. Corrientes 1219</span>, <span class=\"postal-code\">C1043AAM</span> <span class=\"locality\">CABA</span>, <span class=\"country-name\">Argentina</span>",
  "formatted_address": "Av. Corrientes 1219, C1043AAM CABA, Argentina",
  "geometry": {
    "location": {
      "lat": -34.6037445,
      "lng": -58.383988199999976
    },
    "viewport": {
      "south": -34.60514058029149,
      "west": -58.3853329302915,
      "north": -34.6024426197085,
      "east": -58.38263496970848
    }
  },
  "icon": "https://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png",
  "id": "125f7a07fb81d10e98cec399869aaa694cb4b61f",
  "name": "Av. Corrientes 1219",
  "place_id": "ChIJC05_5cXKvJURhKX6uVXO7eE",
  "reference": "CmRbAAAA5p8P3NP9ZMf2RjufMeNs8TZCrG4xe5ItjNYkKoYCcD8wpVG_bujknZM_8cj2k1e2Dtqg1bFjzxSkHTgH1o9MYIiBt1_bozOcgKbSXf95KJNttYd-2pg-E_iKxPH5eZHfEhAl0QPng-2n3Es9Q20B7c-ZGhTW6b2CtvBfBZuA_qUSLJvvngXGMA",
  "scope": "GOOGLE",
  "types": ["street_address"],
  "url": "https://maps.google.com/?q=Av.+Corrientes+1219,+C1043AAM+CABA,+Argentina&ftid=0x95bccac5e57f4e0b:0xe1edce55b9faa584",
  "utc_offset": -180,
  "vicinity": "San Nicolas",
  "html_attributions": []
}
var postalCode = getPostalCode(place)
console.log(postalCode)
    
06.11.2017 / 15:17
1

If you are sure that the word postal_code or postal_code_suffix is not elsewhere, but within array types , you can use

var jsonStr = JSON.stringify(obj);
var postalCode = jsonStr.includes('postal_code');
var postalCodeSuffix = jsonStr.includes('postal_code_suffix');

// Se true, existe a palavra postal_code ou postal_code_suffix no seu objeto
var ans = postalCode || postalCodeSuffix;

(If there is a string in JSON as: zip_code_x it will catch too, this can also be a problem)

If you're not sure, you can use the some method that returns true if any of the objects in array returns true for the function passed as a parameter:

// Se true, existe a palavra postal_code ou postal_code_suffix dentro do array types
var ans = obj['address_components'].some( function(addr) { 
  return addr.types.some( function(type) {
      return type === 'postal_code' || type === 'postal_code_suffix';
  });
});

I would particularly use the second option, for being safe .

    
06.11.2017 / 15:12