javascriptjqueryjsonpjson

Javascript search inside a JSON object


I had a JSON string / object in my application.

{"list": [
    {"name":"my Name","id":12,"type":"car owner"},
    {"name":"my Name2","id":13,"type":"car owner2"},
    {"name":"my Name4","id":14,"type":"car owner3"},
    {"name":"my Name4","id":15,"type":"car owner5"}
]}

I had a filter box in my application, and when I type a name into that box, we have to filter the object and display the result.

For example, if the user types "name" and hits search, then we have to search full names in the JSON object and return the array, just like a MySQL search ...

My question is how can I filter the json object by a specified string and return the array....


Solution

  • You could just loop through the array and find the matches:

    var results = [];
    var searchField = "name";
    var searchVal = "my Name";
    for (var i=0 ; i < obj.list.length ; i++)
    {
        if (obj.list[i][searchField] == searchVal) {
            results.push(obj.list[i]);
        }
    }