我的脚本是
<script type="text/javascript">
search = new Vue({
el: '#offers',
data: {
data: [],
authType: '{{uid}}',
key : '1',
with_ : 'district',
},
mounted() {
var self = this;
navigator.geolocation.getCurrentPosition( success, error );
data = {};
data['auth-token'] = this.authType;
data['key'] = this.key;
data['with_'] = this.with_;
function success( position ) {/* geolocation success callback */
var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';
$.getJSON( GEOCODING ).done( function( location ) {
$('#country').html(location.results[0].address_components[5].long_name);
$('#state').html(location.results[0].address_components[4].long_name);
$('#city').html(location.results[0].address_components[2].long_name);
$('#address').html(location.results[0].formatted_address);
$('#latitude').html(position.coords.latitude);
$('#longitude').html(position.coords.longitude);
data['city'] = location.results[0].address_components[2].long_name;
$.ajax({
url: "http://127.0.0.1:8000/alpha/get/",
data: data,
type: "POST",
dataType: 'json',
success: function (e) {
if (e.status == 1) {
}
},
});
$.ajax({
url: "http://127.0.0.1:8000/city/",
method: "GET",
dataType: "JSON",
success: function(e) {
if (e.status == 1) {
self.cities = e.data;
}
},
});
});
}
},
});
</script>
现在有了data['city']
,我将从地理位置传递获得的城市。但我需要与通过ajax请求http://127.0.0.1:8000/city/
获得的城市列表进行比较,并将相应的ID发送为data['city']
而不是名称。
得到json对获取城市名单的回应
{"status": true, "data": [{"id": 1, "name": "Palakkad"}, {"id": 2, "name": "kochi"}]}`
我需要将地理定位中获得的城市与上面的列表进行比较,如果城市存在,我需要将相应的ID作为data['city']
传递。
请帮助我找到相同的解决方案。我在js中很弱,这是我的第一个项目。我是初学者。请帮我提供解决方案?
答案 0 :(得分:1)
如果我理解正确,给定具有城市数据和城市名称的对象,您希望从城市数据中获取匹配城市的ID(如果匹配)。以下功能应该适合您。
通过cities.data
查找名称匹配的条目。如果找到一个,则返回id
,否则返回null
。
const cities = {"status": true, "data": [{"id": 1, "name": "Palakkad"}, {"id": 2, "name": "kochi"}]};
const cityName = 'Palakkad';
function findCity(name) {
const foundCity = cities.data.find(entry => entry.name === name);
return foundCity ? foundCity.id : null;
}
console.log(findCity(cityName));
console.log(findCity('Houston'));