检查输入中的邮政编码是否存在于JSON中并获取类别 [英] Check if zip code in input exists in JSON and get category
本文介绍了检查输入中的邮政编码是否存在于JSON中并获取类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个JSON元素,其中包含一堆与区域"相关联的不同邮政编码.我想做的是允许用户提交其邮政编码,检查JSON元素中是否存在该邮政编码,然后报告其属于哪个区域":
I have a JSON element with a bunch of different zip codes associated with "zones." What I would like to do is allow a user to submit their zip code, check if the zip code exists within the JSON element and then report which "zone" it belongs to if it does:
var zones = [{
"zone": "one",
"zipcodes": ["69122", "69125", "69128", "69129"]
},
{
"zone": "two",
"zipcodes": ["67515", "67516", "67518", "67521"]
}
];
$(function() {
$('#userZip').submit(function(e) {
e.preventDefault();
var userZip = $('input[type="text"]').val();
// Check if zip exists in JSON and report which zone it belongs to
});
});
i {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="userZip">
<i>Enter zip code "69122" as an example</i>
<input type="text" placeholder="zip" />
<input type="submit" />
</form>
推荐答案
You can use Array.find
var zones = [
{
"zone": "one",
"zipcodes": ["69122", "69125", "69128","69129"]
},
{
"zone": "two",
"zipcodes": ["67515", "67516", "67518", "67521"]
}
];
$(function() {
$('#userZip').submit(function(e) {
e.preventDefault();
var userZip = $('input[type="text"]').val();
// find the first zone with the userZip inside its zipcodes list
var zone = zones.find(function(zone) {
return zone.zipcodes.indexOf(userZip) > -1;
});
alert("Zone: " + zone.zone);
});
});
i {
display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="userZip">
<i>Enter zip code "69122" as an example</i>
<input type="text" placeholder="zip" />
<input type="submit" />
</form>
这篇关于检查输入中的邮政编码是否存在于JSON中并获取类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文