简体   繁体   English

使用javascript从本地json文件中过滤数据

[英]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.我将数据存储在本地 json 文件中,我希望能够过滤该 json 数据,而无需将其硬编码到 javascript 文件中 - 这些只是我见过的示例。

This is a short example of my json file:这是我的 json 文件的一个简短示例:

[

    {
        "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.下面的这个过滤器有效,但我不知道如何在 javascript 文件中对数据进行硬编码。 How would I search by 'surgery type' but still keep the json in a json file instead of what is below?我将如何按“手术类型”进行搜索,但仍将 json 保存在 json 文件中,而不是下面的内容?

<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 .如果你只是想加载json文件是不可能的,但是你可以把它作为一个js文件加载,只需要稍微修改一下假设你的json文件名是data.js。 Contents in data.js are blew data.js 中的内容被炸了

 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 html代码是

 <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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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