Using JavaScript to extract information from a local JSON file

I am currently working on developing an application that can function offline. My data is stored in a local JSON file and I am looking to create a filter for this data without having it hardcoded in a JavaScript file. The examples I have come across so far only involve hardcoding the filter criteria.

Here is a brief snippet of my JSON file:

[

    {
        "ID": 1 ,
        "name": "sub conjunctival haemorrhage",
        "score" : 1,
        "surgeryType": ["scleral buckle", "general", "ppv"] 
    },
    {
        "ID": 2,
        "name": "dry eye",
        "score": 5,
        "surgeryType":["general", "pr"]
    }

]

The filter provided below does function, but I am seeking a way to implement this filter without embedding the data directly into the JavaScript file. How can I search by 'surgery type' while keeping the JSON data within a separate JSON file instead of being hardcoded as shown below?

<script>

    var jsonText = '[
              {
                 "ID":1,
                "name":"sub conjunctival haemorrhage",
                "score":1,
                "surgeryType":["scleral buckle","general","ppv"]},
              {
                 "ID":2,
                 "name":"dry eye",
                 "score":5,
                 "surgeryType":["scleral buckle","pr"]}]';

    var jsonArray = JSON.parse(jsonText);

    var surgerySearchTerm = "scleral buckle";
    var filtered = jsonArray.filter(jsonObject => 
    jsonObject.surgeryType.includes(surgerySearchTerm));

    console.log("Filtered below");
    console.log(filtered);
    
    

</script>

Answer №1

If you're looking to load the json file directly, it may not be possible. However, you can treat it as a js file with a simple tweak. Let's say your json file is named data.js. The contents of data.js are as follows:

var jsonArray = [

{
    "ID": 1,
    "name": "sub conjunctival haemorrhage",
    "score": 1,
    "surgeryType": ["scleral buckle", "general", "ppv"]
},
{
    "ID": 2,
    "name": "dry eye",
    "score": 5,
    "surgeryType": ["general", "pr"]
},.....
]

The corresponding HTML code would look like:

<script src='data.js'>
<script>
       var surgerySearchTerm = "scleral buckle";
       var filtered = jsonArray.filter(jsonObject => 
       jsonObject.surgeryType.includes(surgerySearchTerm));

       console.log("Filtered items below");
       console.log(filtered);
</script>

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

Ways to alter the color of an icon when hovering over it

Is there a way to change the color of a material icon inside an IconButton material component when hovering over the IconButton? I've tried adding a class directly to the icon, but it only works when hovering over the icon itself and not the IconButto ...

VueJS added a new object to the array, but the data did not update reactively

Here is my current data layout days: [ { id: 0 name: 'Monday', times: [] }, { id: 1 name: 'Tuesday', times: [] } } I have implemented the following function to append an object to the times array. onT ...

What is the best way to prevent code execution until a value is returned by $.get?

My attempt to read data from a file and store it in an array using jQuery's get function has hit a snag. Since the get function is asynchronous, the code that comes after the $.get call runs before the data is defined. How can I make sure that the cod ...

Is there a way for me to retrieve the widths of all child elements within an HTML document?

I have been working on a JavaScript (jQuery) function to calculate the maximum width of all child and children's-child elements within a specific div element. Here is the code I have written so far: function setBodyMinWidth(name){ var max = 0; $(nam ...

Seamless Integration of Hosted Fields by Braintree

I am currently struggling with setting up Braintree hosted fields on my registration form. Unfortunately, there are significant gaps between the fields which doesn't look appealing. Despite referring to the braintree documentation and guides, I find t ...

Div element to animate and vanish in a flash

I'm attempting to create a smooth slide effect for a div element before it disappears. Below is the code I am currently using: function slideLeft(element) { $("#" + element).animate({ left: "510" }, { duration: 750 }); document.getEle ...

How to incorporate both images and text in a UIPickerView using Swift?

Can anyone provide an example showcasing how to integrate a UIPickerView in swift, including the display of both images and text using JSON for data loading? ...

Incorporate a New Parameter for the Payload in JMeter

Currently, I am setting up a Performance Test using JMeter and encountering an issue. In my specific scenario, the Request Body must be in Json format with a key named 'json'. Unlike Postman where it's easy to provide a key when passing the ...

A technique, such as regular expressions, can be used to detect the quantity of newline characters in the text entered by the user in a text area

I'm trying to figure out how to count the number of newline characters (or whatever is inserted when the user presses the return key) in a textarea's value. I believe I should be using a regular expression for this task, but I'm not very ski ...

A guide on adjusting the timeout for Azure text to speech silence in JavaScript

Currently, I am utilizing Azure SpeechSDK services to convert speech to text transcription using recognizeOnceAsync. The existing code structure is as follows: var SpeechSDK, recognizer, synthesizer; var speechConfig = SpeechSDK.SpeechConfig.fromSubscripti ...

Traverse each child element sequentially using setTimeout or a delay function

Looking to dynamically apply a CSS filter to a list of divs with a delay between each iteration. Here are my attempted solutions: $(this).children().each(function() { $(this).delay(5000).css("-webkit-filter", "brightness(2)"); }); And this alternativ ...

Display an image from the API that rotates when hovered over with the mouse

Currently, I am fetching data from pokeapi.co and dynamically inserting it into a table. This data includes various stats and an image. My goal is to make the image rotate when hovered over. While creating the table, I added an id="pokeImage" dynamically. ...

What is the top choice instead of using the jQuery toggle() method?

After jQuery deprecated the toggle() method, I began searching for alternative ways to toggle classes on Stack Overflow. I came across various other methods to accomplish the same task (Alternative to jQuery's .toggle() method that supports eventData? ...

Steps to create a new window using Raphael JS

Is there a way to create a new window in Raphael similar to using "_blank"? ...

Having trouble retrieving data using a custom URL in Axios with ReactJs

My knowledge of Reactjs is still new and I am currently working on a project using nextjs. I have a component called Trending.js that successfully fetches data from the URL "https://jsonplaceholder.typicode.com/users". However, when I try to change the U ...

"Exploring the process of transferring an ID from one service to another using the select feature in Angular

I need to store the ID I receive from one service into another using the select element. Here is my approach: <select class="form-control" id="select_fac" [(ngModel)]="rep.idfac"> <option selected disa ...

Utilizing only select functions from lodash can be more beneficial than installing the entire library, as it reduces the amount of unnecessary dependencies

While working on my project, I incorporated underscore.js for its functionality. However, I recently discovered the need for Lodash's fill function. The idea of adding Lodash to my project seems excessive due to overlapping features with underscore.js ...

Tips for implementing focusout on multiple elements while avoiding it when switching focus between them

Looking to create a searchable input that displays a dropdown of possible values on focusin, populated by server-side language. Attempted using focusin on elements not involved with the following code: $("body").not($(".dropdownSearch") ...

Sender receives a response from Socket.io

My goal is to have a socket respond only to the sender. Currently, I am working on having the user connect to the server using JavaScript when they visit any webpage. However, I am unsure whether the connection will be reset each time the user reloads th ...

Transmit information from the backend Node.js to the frontend (without using sockets)

Is there a method to transfer data from my socket, for example example.com:8000, to my web server that is not on the same socket at example.com/index.php? I've searched through various codes but have not come across any solutions yet. If you could pro ...