K20GH
K20GH

Reputation: 6271

Search JSON Array based on variable?

I've got a JSON Array that I need to search:

[
{
      "Device_ID":"1",
      "Image":"HTC-One-X.png",
      "Manufacturer":"HTC",
      "Model":"One X",
      "Region":"GSM",
      "Type":"Phone"
   },
   {
      "Device_ID":"2",
      "Image":"Motorola-Xoom.png",
      "Manufacturer":"Motorola",
      "Model":"Xoom",
      "Region":"CDMA",
      "Type":"Tablet"
   },
   {
      "Device_ID":"8",
      "Image":"null",
      "Manufacturer":"Motorola",
      "Model":"Xoom 2",
      "Region":"CDMA",
      "Type":"Tablet"
   }
]

Using the keyword: $_GET['keyword']; I need to be able to do the following. Search the combined value of Manufacturer and Model, ie. Motorola Xoom. Then, for whichever set of values matches this, output them to variables.

For example: If the Keyword was HTC, then it would search the array and output:

$DeviceID = 1 $Image = HTC-One-X.png $Manufacturer = HTC $Model = One
X $Region = GSM $Type = Type

However if the keyword was Motorola, then it would need to output all entries that include Motorola.

What im trying to do, is output a live view of all JSON Array entries, as the user types the keyword. However I want this to run on the users computer to reduce the load on the server.

Does anyone know the best way to go about this?

Upvotes: 1

Views: 698

Answers (2)

Johnny Leung
Johnny Leung

Reputation: 574

Here's a function for filtering the JSON. Displaying the data is up to you.

var devices = <your JSON array>;    

function filter(keyword, data) {
    var filteredArray = [], i, j;
    for (i = 0, j = data.length; i < j; i++) {
        if ((data[i].Manufacturer && data[i].Manufacturer.indexOf(keyword) !== -1) || (data[i].Model && data[i].Model.indexOf(keyword) !== -1)) {
            filteredArray.push(data[i]);
        }
    }
    return filteredArray;
}

// Example usage
var MotorolaDevices = filter('Motorola', devices);

Upvotes: 1

Gon&#231;alo Vieira
Gon&#231;alo Vieira

Reputation: 2249

well if you have a selection box with the values for the manufacturer in the options section it's as easy as:

HTML:

<select id="selectionBox">
  <option>...</option>
</select>
<div id="outPut">
  output goes in here
</div>

Javascript:

var selectedValue = document.getElementById("selectionBox").value;
for(var i = 0; i < jsonObject.length; i++){
  if(jsonObject[i].Manufacturer === selectedValue){
    //considering your object is an array let's
    for(var key in jsonObject[i]){
      document.getElementById("outPut").innerHTML += jsonObject[i][key] + "</br>";
    }
  }
}

that'll pretty much print everything in the object onto the output div, the rest is up to your styling.

Upvotes: 1

Related Questions