简体   繁体   English

如何将数据从 JSON 文件传递到 JavaScript class

[英]How to pass data from a JSON file to a JavaScript class

I have a local JSON file with the following structure:我有一个具有以下结构的本地 JSON 文件:

{ "project_id": 324,
  "project_name": "Project",
  "contributors": [
       { "name": "James", "dpto": "dpto1" },
       { "name": "Carl", "dpto": "dpto2" }] }

and a class project, which I'm not sure should be like this:和一个 class 项目,我不确定它应该是这样的:

class project {
     constructor(id, name, contributors){
        this.id = id;
        this.name = name;
        this.contributors = contributors; 

Now, I can work with the data after using fetch, but I do not know how to use it outside of the response.现在,我可以在使用 fetch 后处理数据,但我不知道如何在响应之外使用它。

I want to fetch the JSON file and put it into a class I can use outside the response.我想获取 JSON 文件并将其放入 class 我可以在响应之外使用。 Something like:就像是:

.fetch('project.json')
   .then(function (response) {
       return response.json();
   })
   .then(function (data) {
      // Class Project = data;
   })
   .catch(function (err) {
      console.log('error: ' + err);
});

//The data now can be used directly through the class.
Project.CallFunction();

I need to make quite a few manipulations with this data, and I'm not well versed in JavaScript, so I wanted to bring it to a more familiar territory and having something more tangible would make it easier to use.我需要对这些数据进行相当多的操作,而且我对 JavaScript 不是很熟悉,所以我想把它带到一个更熟悉的领域,有一些更具体的东西会更容易使用。

You could have either a constructor that takes the JSON or a static method that returns an instance of the class from the data.您可以有一个采用 JSON 的构造函数,也可以有一个从数据中返回 class 实例的 static 方法。

Taking your example, that would mean:以你的例子为例,这意味着:

const project = await fetch('project.json')
   .then(function (response) {
       return response.json();
   })
   .then(function (data) {
      return new Project(data);
   })
   .catch(function (err) {
      console.log('error: ' + err);
   });

project would then be an instance of the Project class and contain the data. project将成为Project class 的一个实例并包含数据。

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

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