且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

搜索的Javascript对象中的数组与SQL通过对象键

更新时间:2023-01-17 15:04:14

如果你想使用 $的grep 你可以做这样的:

  $(#查询)。在('KEYUP',函数(){
    VAR搜索= this.value.toLowerCase();
    VAR的结果= $ .grep(关键字,功能(EL){
        返回el.keyword.toLowerCase()的indexOf(搜索)GT。 -1;
    });
});

演示: http://jsfiddle.net/9TPSa/

另外请注意,我切换到 KEYUP 事件能够读取更新 THIS.VALUE

For example, i have an array like this:

var arr = [
    {"keyword": "Sample 1", "item": {"title":"Sample Title", "url": "/sample"}},
    {"keyword": "Foo 1", "item": {"title":"Foo Title", "url": "/sample"}}
];

I want to search in the "keyword" key, like when a user presses a key from their input and return that matches objects.

If user presses to "s" key, then first [0], element must return. Like using the SQL LIKE statement.

$("#query").on('keypress', function () {
    var result = $.grep(keywords, function(e){
    //I do not know what should i do here.    
    });
});

If you want to use $.grep you can do it like this:

$("#query").on('keyup', function() {
    var search = this.value.toLowerCase();
    var result = $.grep(keywords, function(el) {
        return el.keyword.toLowerCase().indexOf(search) > -1;
    });
});

Demo: http://jsfiddle.net/9TPSa/

Also note, that I switched to keyup event to be able to read updated this.value.