Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

118
Visualizações
How to pass data from a JSON file to a JavaScript class

I have a local JSON file with the following structure:

{ "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 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.

I want to fetch the JSON file and put it into a class I can use outside the response. 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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You could have either a constructor that takes the JSON or a static method that returns an instance of the class from the data.

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda