我想从用户提供的所有输入中搜索房屋名称。 因此,如果用户详细信息如下:
[{"houseName":"man","houseType":"别墅","houseFloors":"七","houselocation":"西雅图"},{"houseName":"band","houseType":"小","houseFloors":"二","houselocation":"华盛顿特区"}]
如果我以 man 的身份提供搜索,它应该给我:
[{"houseName":"man","houseType":"别墅","houseFloors":"七","houselocation":"西雅图"}]
代码如下:
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>House Name
<input type='text' name='houseName' id='houseName' placeholder="House Name">
</label>
<br>
<br>
<label>House type
<input type='text' name='houseType' id='houseType' placeholder="House type">
</label>
<br>
<br>
<label>House Floors:
<input type='text' name='houseFloors' id='houseFloors' placeholder="House Floors">
</label>
<br>
<br>
<label>House Location:
<input type='text' name='houselocation' id='houselocation' placeholder="House Location">
</label>
<br>
<br>
<div>
<label>search:
<input type="text" name="search" id="search-input" placeholder="search">
<input type="submit">
</div>
<button type="button" id="add">Add Details</button>
<button type="button" id="print">Show</button>
<pre></pre>
<script>
var list = [],
$ins = $('#houseName, #houseType, #houseFloors, #houselocation'),
var counter = {
houseName: {},
houseType: {},
houseFloors: {},
houselocation: {}
};
$('#add').click(function() {
var obj = {},
valid = true;
$ins.each(function() {
var val = this.value;
if (val) {
obj[this.id] = val;
} else {
alert(" Cannot be blank");
return false;
}
});
if (valid) {
list.push(obj);
$ins.val('');
}
});
$('#print').click(function() {
$('pre').text(JSON.stringify(list) + '\n\n');
})
var keyword = $('#search-input').val();
var filteredList = list.filter(function(user){
return user.houseName === 'man'; // Or u can use indexOf if u want check if the keyword is contained
});
</script>
</body>
</html>
最佳答案
您可以使用Array.prototype.filter
。
在你的情况下,它看起来像
var filteredList = list.filter(function(user){
return user.houseName === 'man'; // Or u can use indexOf if u want check if the keyword is contained
});
如果您想使用输入框进行搜索,则还需要做一些工作:
//The follow code should be executed when u are going to do the 'search' action
//It could be an click on a button, or just in a listener which is triggered when the search box fires 'change' events
//First u need to get the keyword from the search input box:
var keyword = $('#search-input').val();
//maybe do some value check
//if (keyword === '') return;
//then get the filtered List
var filteredList = list.filter(function(user){
return user.houseName === keyword;
});
//Finally update the UI based on the filtered List
//Maybe jQuery's DOM functions could be helpful
关于javascript - 我想从 javascript 中的 json 对象中搜索字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38279850/