简体   繁体   English

如何使用jquery搜索json数据

[英]how to search in json data using jquery

I want to search in json data on every keyup. 我想在每个键盘上搜索json数据。

Json: 杰森:

{
 "AB01": {
   "foo": "bar",
   "ID": "A1",
   "PID": "Z09",
    },
  "AB10": {
    "foo10": "bar10",
    "ID": "B10",
    "PID": "Y08",
   },
}

jQuery jQuery的

$('input').on('keyup', function(){
  $.getJSON("ABc.json", function(data) {
    var InputVal = $('input').val();
    var myExp = new RegExp(InputVal, "i");

    var results = [];

    $.each(data, function(key, obj){
        if (obj.foo.search(new RegExp(InputVal,"i")) != -1) {
            results.push(obj);
        }       
    });

    for(var i=0; i< $(results).length; i++)
    {
     console.log(JSON.stringify(results[i])); 
    }
  });
});

Html: HTML:

<input type="text" name="abc">


Now i want that the input string\\char on every keyup match data in json not with foo or ID but with all key and value. 现在我希望on every keyupinput string\\char匹配json中的数据,而不是fooID而是所有键和值。


I can't find how to solve this, any help appreciated. 我找不到解决方法,不胜感激。
If any thing you want from my side let me know :) 如果您想在我这边做任何事情,请告诉我


Thanks in advance. 提前致谢。

You are trying to do a string comparison on an object. 您正在尝试对对象进行字符串比较。

You need an inner iteration of each property of those objects. 您需要这些对象的每个属性的内部迭代。

$.each(data, function(key, obj){
    var hasMatch = false;
    // use any object property iteration approach to check each value
    $.each(obj, function(key,val){
       if (val.search(new RegExp(InputVal,"i")) != -1) {
          hasMatch = true;
          return false; // break the loop, we have a match
       }  
    });
    if(hasMatch){
       results.push(obj);
    }            
});

There are other array methods like filter() you could use but I kept it in same format as your current code 还有其他一些可以使用的数组方法,例如filter(),但我将其保留为与当前代码相同的格式

Also note that you should load the data in advance so you don't need to request it each time 另请注意,您应该提前加载数据,这样就不必每次都请求

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM