#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2008
    Posts
    55
    Rep Power
    7

    Question Search through JSON Array using Javascript 'like' operator?


    So here's my problem.
    I have an search box which has the JavaScript variable search_input assigned to it.

    I've then got my JSON Encoded Array named devices as so:

    Code:
        var devices = [{"Device_ID":"43","Image":"Amazon-Kindle-Fire.png","Manufacturer":"Amazon","Model":"Kindle Fire","Type":"Tablet"},{"Device_ID":"69","Image":"Asus-Nexus-7.png","Manufacturer":"Asus","Model":"Nexus 7 ","Type":"Tablet"},{"Device_ID":"40","Image":"Asus-Transformer.png","Manufacturer":"Asus","Model":"Transformer","Type":"Tablet"},{"Device_ID":"41","Image":"Asus-Transformer-Prime.png","Manufacturer":"Asus","Model":"Transformer Prime","Type":"Tablet"}]
    On my page, I have some more JavaScript which reads through the array and writes it to a page as so:

    Code:
         	for(var i=0;i<devices.length;i++){
            		    var device_id = devices[i].Device_ID;
    	        		var image = devices[i].Image;
    	        		var manufacturer = devices[i].Manufacturer;
    	        		var model = devices[i].Model;
    	        		var type = devices[i].Type;
    	        		
    	        		document.write(+device_id+'-'+image+'-'+manufacturer+'-'+model+'-'+type+);
    		}
    This so far works great, it shows everything in the array, just how I want it.

    What I need to do now though, is when someone types something into the search_box, I need it to effectively filter the array by the concatenation of Manufacturer & Model by what they have searched for so the JavaScript above, only shows the array content of what they are searching.

    The other issue is that it needs to be a 'LIKE' statement as you would have it in SQL. So if a user searched from Ama it would still return Amazon Kindle Fire, 7 would bring back Asus Nexus 7, N would bring back everything with N in it etc.
  2. #2
  3. No Profile Picture
    Lost in code
    Devshed Supreme Being (6500+ posts)

    Join Date
    Dec 2004
    Posts
    8,316
    Rep Power
    7171
    JavaScript doesn't have a LIKE operator, but you can achieve a similar result by simply searching the string to see whether it contains the search term. For example:
    Code:
    (string_to_test.indexOf(search_term) !== -1)
    If that statement is true, then search_term is contained within string_to_test; otherwise it is not. This would be similar to doing:
    Code:
    column_to_test LIKE '%search_term%'
    in a SQL query.
    PHP FAQ

    Originally Posted by Spad
    Ah USB, the only rectangular connector where you have to make 3 attempts before you get it the right way around

IMN logo majestic logo threadwatch logo seochat tools logo