I'm writing this code to find the long-name of "types" : [ "locality", "political" ]
and long-name of "types" : [ "administrative_area_level_2", "political" ]
from the json file. but unable to iterate through the array properly
我编写这段代码是为了从json文件中找到“类型”的长名称:[“局部性”,“政治性”]和“类型”的长名称:[" administration ative_area_level_2", "political"]。但是不能正确地遍历数组。
js file
js文件
var request = require('request');
request('http://maps.googleapis.com/maps/api/geocode/json?latlng=23.6519148,87.13857650000001', function(error, response, data) {
if (!(!error && response.statusCode == 200)) {
console.log('error! ');
return;
}
data = JSON.parse(data);
for (var i in data.results) {
for (var j in data.results[i]) {
if (j == 'address_components') {
console.log('found')
console.log(data.results[i][j][1]);
console.log(data.results[i][j][2]);
for (var k in data.results[i]){
if(k == 'long_name')
console.log('found')
}
console.log('not found')
}
}
break;
}
});
output
输出
found
{ long_name: 'Kunustoria',
short_name: 'Kunustoria',
types: [ 'locality', 'political' ] }
{ long_name: 'Bardhaman',
short_name: 'Bardhaman',
types: [ 'administrative_area_level_2', 'political' ] }
not found
2 个解决方案
#1
1
Replace your for loop with this...
用这个替换你的for循环…
data = JSON.parse(data).results;
data.forEach(function (address) {
console.log(address['address_components'][0].long_name);
});
#2
0
First you must install lodash.
首先必须安装lodash。
npm install --save lodash
npm安装,节省lodash
var _ = require('lodash');
var data = api_response_from_google_maps;//Assign the api response here.
var addrs = [];
_.map(data.results, function (address) {
_.map(address.address_components, function (item) {
if (_.isEqual(item.types, ["locality", "political"]) || _.isEqual(item.types, ["administrative_area_level_1", "political"])) {
addrs.push(item);
}
})
});
console.log(JSON.stringify(addrs));
This gives an array of objects of adresses_components
with types
array as you specified.
这将提供adresses_components的对象数组和指定的类型数组。
#1
1
Replace your for loop with this...
用这个替换你的for循环…
data = JSON.parse(data).results;
data.forEach(function (address) {
console.log(address['address_components'][0].long_name);
});
#2
0
First you must install lodash.
首先必须安装lodash。
npm install --save lodash
npm安装,节省lodash
var _ = require('lodash');
var data = api_response_from_google_maps;//Assign the api response here.
var addrs = [];
_.map(data.results, function (address) {
_.map(address.address_components, function (item) {
if (_.isEqual(item.types, ["locality", "political"]) || _.isEqual(item.types, ["administrative_area_level_1", "political"])) {
addrs.push(item);
}
})
});
console.log(JSON.stringify(addrs));
This gives an array of objects of adresses_components
with types
array as you specified.
这将提供adresses_components的对象数组和指定的类型数组。