简体   繁体   中英

filtering data from a local json file with javascript

What i'm trying to do is create an app that can be used offline. I have my data stored in a local json file and I would like to be able to filter that json data without it being hardcoded in a javascript file- these are only the examples I have seen for this.

This is a short example 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"]
    }

]

this filter below works but I don't know how to do it without hardcoding the data in the javascript file. How would I search by 'surgery type' but still keep the json in a json file instead of what is 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>

If you just want to load the json file is impossible,but you can loaded it as a js file ,and only need a little modification Suppose your json file name is data.js . Contents in data.js are blew

 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 html code are

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM