Javascript search inside a JSON object

ramesh picture ramesh · May 21, 2012 · Viewed 155.1k times · Source

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 to filter the json object with string and return the array....

Answer

McGarnagle picture McGarnagle · May 21, 2012

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]);
    }
}