如何从Angular 2中的JSON对象中读取想要的数据?

时间:2016-05-29 15:59:35

标签: javascript angularjs json

我在阅读和记录这样的JSON文件时遇到了问题:

{
"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"
  }

我只需要城市名称,而不是所有这些数据。我怎么能只记录想要的对象行。

我试过这段代码,但这并不像我想要的那样:

Object.keys(JSON[0]);

2 个答案:

答案 0 :(得分:1)

对于您的示例数据

>> data['results'][0]['address_components'][2]['long_name']
Williamsburg

>> data['results'][0]['address_components'][3]['long_name']
Brooklyn

如果您将数据作为JSON字符串获取,则需要在

之前将其转换为JavaScript对象
data = JSON.parse(the_json_string_here);

答案 1 :(得分:1)

您可以按sublocality_level_1进行过滤,并在函数中执行此操作,以便在收到类似的不同JSON时重复使用它。

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);