Using jQuery.find() on array or similar

Lets say I have a search box and whatever is typed in it is stored as:

var search_input = $(this).val();

How would I search my array with this value?

var devices = [{"Device_ID":"43","Image":"Amazon-Kindle-Fire.png","Manufacturer":"Amazon","Model":"Kindle Fire","Type":"Tablet"},{"Device_ID":"44","Image":"Apple-iPad.png","Manufacturer":"Apple","Model":"iPad","Type":"Tablet"}]

So lets say I had Amazon, or Kindle etc in my search_input variable, I would want it to search the array and output the below. The same would apply for any thing typed or anything in the array

<div id="device">43</div>
<div id="image">Amazon-Kindle-Fire.png</div>
<div id="name">Amazon Kindle Fire</div>

Answer

Simple loop in a loop

var devices = [{"Device_ID":"43","Image":"Amazon-Kindle-Fire.png","Manufacturer":"Amazon","Model":"Kindle Fire","Type":"Tablet"},{"Device_ID":"44","Image":"Apple-iPad.png","Manufacturer":"Apple","Model":"iPad","Type":"Tablet"}];

function findItem (term) {
    var items = [];
    for (var i=0;i<devices.length;i++) {
        var item = devices[i];
        for (var prop in item) {
            var detail = item[prop].toString().toLowerCase();
            if (detail.indexOf(term)>-1) {
                items.push(item);
                break;               
            }
        }
    }
    return items;
}

console.log( findItem("amazon") );  //returns one item
console.log( findItem("kindle") );  //returns one item
console.log( findItem("apple") );   //returns one item
console.log( findItem("tablet") );  //returns two items
console.log( findItem("nerd") );    //returns zero items
​

jsFiddle

Leave a Reply

Your email address will not be published. Required fields are marked *