我想从存储在 javascript 的 json 对象中的数组中搜索用户关键字

I want to search an user keyword from array stored in a json object in javascript

本文关键字:数组 搜索 用户 关键字 对象 json 存储 javascript      更新时间:2023-09-26

这是输出:

[{"houseName":"a","houseType":"b","houseFloors":"c","houselocation":"d"},{"houseName":"p","houseType":"q","houseFloors":"r","houselocation":"s"}]

我的代码是:

<html lang>
<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>
<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');
})

</script>
</body>
</html>

现在我想要的是当用户提供一个关键字时,我想通过javascript中的这个输出搜索该特定关键字,并返回该特定对象的完整详细信息。

例如:如果关键字是:a输出应为:[{"房屋名称":"a","房屋类型":"b","房屋楼层":"c","房屋位置":"d"}]

下面的代码应该可以工作

var arr = [{"houseName":"a","houseType":"b","houseFloors":"c","houselocation":"d"},{"houseName":"p","houseType":"q","houseFloors":"r","houselocation":"s"}]

function queryObject(prop, key)  {
var returnThis;
for(var i=0, len = arr.length; i< len; i++) {
if(arr[i][prop] === key) {
returnThis = arr[i]
} 
return returnThis
}
}
$('input').on('change', function() {
var prop = $(this).attr('id');
var key = $(this).val();
queryObject(prop,key)
});

对于通用解决方案,只需对output数组进行过滤即可

var keyword = "a";
var result = output.filter( function(obj){
  return Object.keys(obj).filter( function(key){
    return obj[ key ].indexOf( keyword ) != -1;
  }).length > 0;
});
//now result has the filtered array
console.log( result );

演示

var output = [{"houseName":"a","houseType":"b","houseFloors":"c","houselocation":"d"},{"houseName":"p","houseType":"q","houseFloors":"r","houselocation":"s"}];
var keyword = "a";
var result = output.filter( function(obj){
  return Object.keys(obj).filter( function(key){
    return obj[ key ].indexOf( keyword ) != -1;
  }).length > 0;
});
//now result has the filtered array
console.log( result );