我有一个像这样定义的JSON数组:
var neighbourhood = [
{"result": "A good one", "streetname": ["First Street", "Second Street"]},
{"result": "A bad one", "streetname": ["Lorem Street", "Ipsum Street"]},
{"result": "Undecided", "streetname": ["Ketchup Street"]}
];
我正在尝试创建一个可以输入街道名称并输出结果的网络应用程序。例如,如果您输入“Lorem Street”,我需要返回“A bad one”。
我明确地避免使用SQL和PHP,那么我将如何使用JSON数组在Javascript中执行此操作?
谢谢!
答案 0 :(得分:1)
var neighbourhood = [
{"result": "A good one", "streetname": ["First Street", "Second Street"]},
{"result": "A bad one", "streetname": ["Lorem Street", "Ipsum Street"]},
{"result": "Undecided", "streetname": ["Ketchup Street"]}
];
function getStreetResult(street) {
for(var i = 0; i < neighbourhood.length; i++) {
if(neighbourhood[i].streetname.indexOf(street) >= 0) {
return neighbourhood[i].result;
}
}
}
alert(getStreetResult('Lorem Street'));
答案 1 :(得分:1)
正常情况下的替代品&#39;循环,您可以使用filter
。
function getResult(name) {
var result = neighbourhood.filter(function (el) {
return el.streetname.indexOf(name) > -1;
});
return result.length > 0 ? result[0].result : false;
}
getResult('Lorem Street'); // A bad one
编辑:如果未找到匹配,则返回false。
答案 2 :(得分:0)
请试试这个。非常感谢
<script>
var neighbourhood = [
{"result": "A good one", "streetname": ["First Street", "Second Street"]},
{"result": "A bad one", "streetname": ["Lorem Street", "Ipsum Street"]},
{"result": "Undecided", "streetname": ["Ketchup Street"]}
];
function submit(){
var str = document.getElementById('txt').value;
neighbourhood.forEach(function(neighbour){
neighbour.streetname.forEach(function(street){
if (str==street)
{
alert(neighbour.result);
return;
}
})
})
}
</script>
<input type="text" id="txt">
<br>
<button onclick="submit()">Submit</button>