vikasde vikasde - 4 months ago 26
Javascript Question

How to efficiently search a JSON array

The following code works fine:

var stores = new Array();
stores[0] = { ItemNumber: "2001", Code: "001", Qty: "1", OH: "1" };
stores[1] = { ItemNumber: "2002", Code: "002", Qty: "3", OH: "2" };
stores[2] = { ItemNumber: "2003", Code: "003", Qty: "5", OH: "8" };
stores[3] = { ItemNumber: "2001", Code: "004", Qty: "10", OH: "90" };

var item = "2001";
var code = "001";

var searchResult = jQuery.grep(stores, function (store, indexInArray) {
var found = false;
if (item != "" && code != "") {
found = (store.Code == code) && (store.ItemNumber == item);
}
else if (item != "" && code == "") {
found = (store.ItemNumber == item);
}
else if (code != "" && item == "") {
found = (store.Code == code);
}
return found;
});

$.each(searchResult, function (index, obj) {
console.log("found: " + obj.Code);
});


JSFiddle: http://jsfiddle.net/hwpnbkm3/

However I am not really happy with the code, because there are way too many if/else statements. Also if I wanted to search by Qty or OH, then it will get even more complicated. Is there a way to search through this array without the multiple if/else statements? Can I maybe build a dynamic query to search through the array?

Answer

Your function could be simplified to:

return (item == "" || store.ItemNumber == item) &&
       (code == "" || store.Code == code) &&
       (item != "" || code != "");

But what I would recommend instead is this: Instead of having individual variables for your query, make an object.

var stores = new Array();
stores[0] = { ItemNumber: "2001", Code: "001", Qty: "1", OH: "1" };
stores[1] = { ItemNumber: "2002", Code: "002", Qty: "3", OH: "2" };
stores[2] = { ItemNumber: "2003", Code: "003", Qty: "5", OH: "8" };
stores[3] = { ItemNumber: "2001", Code: "004", Qty: "10", OH: "90" };

var query = { ItemNumber: "2001", Code: "001" };

var searchResult = jQuery.grep(stores, function (store, indexInArray) {
    var found = false;
    for(var n in query) {
      if(query[n] != "") {
        if(query[n] != store[n]) {
          found = false;
          break;
        }
        found = true;
      }
    }
    return found;
});

$.each(searchResult, function (index, obj) {
    console.log("found: " + obj.Code);
});
Comments