简体   繁体   中英

Searching through objects, client-side?

I have 50-100 objects in memory client-side. I need to search them without tags, just text searching every field of the object and finding matches or partial matches.

What is the best way to do this type of search, how can I list them based on relevance?

Elements:

If you want to look for text within elements, try this:

$(":contains('your text')");

This will return each element that contains your text .

Objects

See this demo: http://jsfiddle.net/datyn/1/

Also searches for sub objects, currently searches Case Insensitive, if you want to change it, just remove the .toLowerCase() functions:

var ob = {
    User : {
        name : "Niels",
        country : "Netherlands"
    },
    Name : "Niels test X"
}

function find_match(search, results)
{
    $.each(this, function(k, v){
       if( typeof(v) == "object" )
       {
            find_match.call(v, search, results);  
       }
        else
        {
             if( v.toLowerCase().indexOf(search.toLowerCase()) != -1)
             {
                 if($.inArray(this, results) == -1)
                 {
                     results.push(this);
                 }   
             }
        }
    });
}

var results = [];
find_match.call(ob, "x", results);
alert("Search for x results: " + results.length);
var results = [];
find_match.call(ob, "n", results);
alert("Search for n results: " + results.length);

You can call the function by using .call method.

Example :

find_match.call("Object / array you want to search", "The string", "Array where the results will be stored")

Changes:

  1. If you don't want to match a part of a string, change: v.toLowerCase().indexOf(search.toLowerCase()) != -1 into v.toLowerCase() == search.toLowerCase()

You might want to take a look at this:

http://goessner.net/articles/JsonPath/

For each object in your collection (with 50-100 I assume they are kept in an array perhaps, or the result of a jQuery selection), use Object.keys to get the property names then grab the associated value and perform your match.

Since your match returns a relevance score, you can place all matches into an array of pairs (match x score) and do an array sort with a comparator set to compare by score.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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