Is it possible to search a JSON Array using a variable as the criteria

I have a JSON Array that needs to be searched:

[
{
      "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 search the combined value of Manufacturer and Model, for example Motorola Xoom. Then, output the matching values to variables.

For instance, if the Keyword was HTC, it would output:

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

If the keyword was Motorola, then all entries containing Motorola should be displayed.

The goal is to show live updates of JSON Array entries as the user types keywords, but run this on the user's computer to reduce server load.

Any suggestions on the best way to accomplish this?

Answer №1

Managing a selection box with manufacturer values is quite simple:

Use the following HTML:

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

Incorporate the Javascript code:

var selectedValue = document.getElementById("selectionBox").value;
for(var i = 0; i < jsonObject.length; i++){
  if(jsonObject[i].Manufacturer === selectedValue){
    //assuming your object is an array, iterate through its keys
    for(var key in jsonObject[i]){
      document.getElementById("outPut").innerHTML += jsonObject[i][key] + "</br>";
    }
  }
}

This will display all object contents in the output div. The styling can be customized according to your preferences.

Answer №2

Implement this function to filter JSON data as needed, the presentation is open-ended.

var gadgets = <your JSON array>;    

function screening(desiredTerm, info) {
    var refinedList = [], x, y;
    for (x = 0, y = info.length; x < y; x++) {
        if ((info[x].Brand && info[x].Brand.indexOf(desiredTerm) !== -1) || (info[x].Model && info[x].Model.indexOf(desiredTerm) !== -1)) {
            refinedList.push(info[x]);
        }
    }
    return refinedList;
}

// Sample implementation
var MotorolaDevices = screening('Motorola', gadgets);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to generate a JsonObject because of a java.lang.IllegalStateException error indicating that it is not a JSON Object

I have encountered an issue with my code involving the "Ocupacion" object class that contains other attributes (although it is a large class and I cannot list all of its attributes here). public String genHor(){ Collection<Ocupacion> ocupas = ne ...

jQuery unable to access data from cross-origin JSON service URL

Similar Question: Issues with JQuery not receiving JSON data? <script type="text/javascript> var url = "http://local.yahooapis.com/LocalSearchService/V3/localSearch?appid=YahooDemo&query=pizza&zip=10504&results=2&output=j ...

What is the process for enabling multiple consumers to subscribe to a shared topic in RabbitMQ and receive identical messages?

Although there is a similar question with an answer here, I remain uncertain whether the limitation lies in RabbitMQ's capabilities or if I simply need to conduct further research. Coming from a JS/Node background where the event pub/sub pattern func ...

Issues encountered with Nextjs 13.4 and Next-Auth 4.2 regarding the signIn("credentials", { }); functionality not functioning as expected

When using next-auth credentials in my current project, I encountered an issue with the signIn() function from next-auth/react. It appears that the redirection to the admin page persists regardless of whether the login details are correct or not. {error: n ...

I encounter Error 406 and CORS issues when making API calls

I am currently engaged in a project aimed at helping my employer keep track of shipping loads, customers, carriers, and locations. The frontend is built using a react app that enables users to input information regarding loads, customers, etc. On the backe ...

Making a REST call with values containing an apostrophe

Currently, I am utilizing REST and ajax to retrieve data from SharePoint using the URL below: https:xxxxxxxx/_vti_bin/ListData.svc/RMSD_Tasks?$orderby=IssueValue asc,StatusValue desc&$filter="+dropValue+" eq '"+secondFilterVal+"'&groupby ...

How to Display a Modal Window Automatically Using Bootstrap.js?

Recently, I've become interested in using the Bootstrap library by Twitter for my simple web page. My goal is to have a modal window automatically display after the page loads. If anyone has any tips on how to achieve this, I would greatly appreciate ...

Error: The function setEmail is not defined. (In 'setEmail(input)', 'setEmail' is not recognized) (Cannot utilize hooks with context API)

App.js const[getScreen, showScreen] = useState(false); const[getEmail, setEmail] = useState(""); <LoginScreen/> <LoginContexts.Provider value={{getEmail,setEmail,getScreen,showScreen}}> {showScreen?<Screen2/>:<LoginScre ...

Automatically activate the next tab in Bootstrap

I have a modal that performs a count. Once the count is completed, the modal closes. My goal is to automatically switch to the next tab in Bootstrap when the modal closes. Here is the HTML: <ul class="nav nav-tabs namelocationtable"> <div clas ...

What is the process for retrieving User Information using AngularJS following NodeJS authentication?

While I've come across similar questions on this topic, my lack of experience with Angular and Node is making it difficult for me to find a suitable solution. I had previously written this code that successfully handled the login process and allowed ...

Jquery is not displaying the background color of the progress bar

Greetings to all! I am currently working on implementing a progress bar for my website, but I am encountering an issue where the background-color is not displaying correctly on scroll. I would greatly appreciate any assistance with this matter. Below you c ...

Tips for presenting a JSON object within a scrollView

I need to arrange each JSON object in a separate horizontal scroll view This means displaying id, resType, name, and URL in their own individual horizontal scroll views. So, there will be a total of 4 horizontal scroll views. JsonObjectRequest jor ...

JavaScript maintain a variable that holds onto nodes even after they have been removed

Recently, I encountered a seemingly simple issue with JavaScript that has me stumped. In my code, I have a variable that stores nodes with a specific class. My goal is to remove these nodes from the DOM while still retaining them in the variable. However, ...

Creating an array of logos in ReactJS with the help of TailwindCSS

After seeing multiple implementations of this feature, I find myself struggling to search for a solution. I can only access the HTML and CSS through inspecting elements, wondering if others are facing the same issue as me. Typically, we aim to implement t ...

Identifying the Click Event Within an ngx Bootstrap Modal

I recently set up an ngx bootstrap modal using the instructions provided in this helpful guide - . However, I'm facing a challenge in detecting click events within the modal body once it's open. Below is the code snippet from my app component. D ...

Is there a simple method for transforming tabular data from an Excel spreadsheet into JSON format?

I'm looking to transform data from a spreadsheet in either Excel or Open Office that's saved as *.xls into *.json format. The information is not confidential The file size is manageable ...

Transferring Android Json object and Json array through an httppost request

I have a database containing some data that I need to send in JSON format. Currently, I am sending each record individually, but I want to send all the records at once to a web API. How can I convert these records into a JSON array dynamically and post the ...

Mapping an array element to a string using Codable object

I am facing a peculiar issue where my back-end returns an object structured like this: { "user": { "name": [ "John" ], "familyName": [ "Johnson" ] } } Each property is presented as an array cont ...

Each time the page is reloaded, an error message pops up: "TypeError: Cannot access attributes of an undefined object (referencing 'name')."

Everything seems to be working fine in my app, except for one issue when I try to refresh the page where an event is being edited (EditEvent Component). The error message I receive is: Uncaught TypeError: Cannot read properties of undefined (reading ' ...

Obtain a custom token after next authentication through Google login

Utilizing next js, next auth, and a custom backend (flask), I have set up an API Endpoint secured with jwt token. In my next js frontend, I aim to retrieve this jwt token using the useSession hook to send requests to these API Endpoints. Everything functio ...