我有一个 JSON 元素,其中包含与“区域”关联的一堆不同的邮政编码。我想做的是允许用户提交他们的邮政编码,检查邮政编码是否存在于 JSON 元素中,然后报告它属于哪个“区域”(如果存在):
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>
最佳答案
您可以使用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>
关于javascript - 检查输入中的邮政编码是否存在于 JSON 中并获取类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43873107/