json列表过滤器包含给定的文本

时间:2015-08-27 13:21:27

标签: javascript jquery json

我有一个清单

var jsonList = [
   {
      "id": "one",
      "pId": "nosearch",
      "cId": "searchc"
   },
   {
      "id": "two",
      "pId": "product1",
      "cId": "searchc"
   },
   {
      "id": "three",
      "pId": "product2",
      "tId": "searcht"
   }
]

我想获取包含给定文本的所有项目的列表。 例如,如果我搜索'搜索',则应返回所有项目。如果我搜索产品,则应返回第二项和第三项。

像search(jsonList,searchText)这样的函数会实现这个吗?

3 个答案:

答案 0 :(得分:0)

试试这个

var jsonList = [{
    "id": "one",
    "pId": "nosearch",
    "cId": "searchc"
}, {
    "id": "two",
    "pId": "product1",
    "cId": "searchc"
}, {
    "id": "three",
    "pId": "product2",
    "tId": "searcht"
}]
function search(jsonList, searchText) {
    return jsonList.filter(function(x) {
        for (var i in x) {
            if (x[i].toLowerCase().indexOf(searchText.toLowerCase()) > -1) return x;
        }
    })
}
console.log(search(jsonList, 'search'))

答案 1 :(得分:0)

搜索对象:

var obj = {
     'one':1,
    'two': 1,
    'three': 2
}

console.log(matches(obj, 1));

function matches(obj, str){
    var ret = new Array();
    for(var key in obj){
         if(obj[key] == str){
              ret.push(key);
         }
    }
    return ret;
}

http://jsfiddle.net/aqmxqkcz/

答案 2 :(得分:0)

试试这个( Prototype方式Case Insensitive ):

var data = [{
    "id": "one",
        "pId": "nosearch",
        "cId": "searchc"
}, {
    "id": "two",
        "pId": "product1",
        "cId": "searchc"
}, {
    "id": "three",
        "pId": "product2",
        "tId": "searcht"
}]

Array.prototype.find = function (str) {
    return this.filter(function (elem) {
        for (var i in elem) {
            var strRegExPattern = '\\b' + str + '\\b';
            var pattern = new RegExp(strRegExPattern, "i")
            if (elem[i].match(pattern)) {
                return this;
            }
        }
    });
}

console.log(data.find('searchc'));

Fiddle