How to check if an object has a string?

Asked

Viewed 386 times

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 inside the "address_components" there are the types "postal_code" or "postal_code_suffix".

What I did was go through the objects but I can’t find the postal_code or the 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('');
    }
  }
}
  • 1

    It’s too generic to do JSON.stringify(obj).includes('postal_code')?

2 answers

1

In case you’re sure the word postal_code or postal_code_suffix is nowhere else but within the 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 the JSON as: postal_code_x it will catch also, this can also be a problem)


If you are not sure, you can use the method some returning true case any of the objects in the array return true for the function passed as 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 more sure.

1


You can use the find to find the objects you own postal_code or postal_code_suffix in the array types and use them to return the postcode.

Using the function getPostalCode 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)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.