Morteza Aghili Morteza Aghili - 6 months ago 26
JSON Question

How to just read wanted data from JSON object in Angular 2?

I have a problem in reading and logging JSON file like this:

{
"results" : [
{
"address_components" : [
{
"long_name" : "277",
"short_name" : "277",
"types" : [ "street_number" ]
},
{
"long_name" : "Bedford Avenue",
"short_name" : "Bedford Ave",
"types" : [ "route" ]
},
{
"long_name" : "Williamsburg",
"short_name" : "Williamsburg",
"types" : [ "neighborhood", "political" ]
},
{
"long_name" : "Brooklyn",
"short_name" : "Brooklyn",
"types" : [ "sublocality_level_1", "sublocality", "political" ]
},
{
"long_name" : "Kings County",
"short_name" : "Kings County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "New York",
"short_name" : "NY",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "11211",
"short_name" : "11211",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "277 Bedford Ave, Brooklyn, NY 11211, USA",
"geometry" : {
"location" : {
"lat" : 40.714232,
"lng" : -73.9612889
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 40.7155809802915,
"lng" : -73.9599399197085
},
"southwest" : {
"lat" : 40.7128830197085,
"lng" : -73.96263788029151
}
}
},
"place_id" : "ChIJd8BlQ2BZwokRAFUEcm_qrcA",
"types" : [ "street_address" ]
},
],
"status" : "OK"
}


I just need the name of city, not all of this data. How could I log just wanted object row.

I tried this code but that doesn't work like I want:

Object.keys(JSON[0]);

Answer

You can filter by sublocality_level_1 and do it in a function to reuse it if you receive a similar JSON sorted different.

const getCity = data => data.address_components
      .filter(x => x.types && x.types.indexOf("sublocality_level_1") > -1)
      .map(x => x.long_name)[0];

//Get a city name from only the first result 
const oneCity = getCity(jsonData.results[0]);

//Get an array with all cities (for all the results)
const allCities = jsonData.results.map(getCity);
Comments