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

130
Visualizações
How to load JSON data in a JavaScript class properties

I have JSON data as follows:

[
  
  {
    "position": 0,
    "symbol": "H",
    "name": "Hydrogen",
    "color": "blue"
  },
  {
    "position": 1,
    "symbol": "He",
    "name": "Helium",
    "color": "cyan"
  }

]

And I want to load it into a class properties defined as follows:

class Element{

    constructor(){

        this.index = Math.floor(Math.random() * 89);
        this.position;
        this.symbol;
        this.name;
        this.color;
        this.loadData();

    }

    loadData(){

        fetch('./json/data.json')
        .then(response => response.json())
        .then(data => {
            this.position = data[this.index].position;
            this.symbol = data[this.index].symbol;
            this.name = data[this.index].name;
            this.color = data[this.index].color;
        });

    }
}

I want that, for example:

constructor(){

    this.index = Math.floor(Math.random() * 89);
    this.position; // 0
    this.symbol; // H
    this.name; // Hydrogen
    this.color; // Blue
    this.loadData();

}

But what happens is the following:

constructor(){

    this.index = Math.floor(Math.random() * 89);
    this.position; // undefined
    this.symbol; // undefined
    this.name; // undefined
    this.color; // undefined
    this.loadData();
    this.exampleMethod();

}

loadData(){

    fetch('./json/data.json')
    .then(response => response.json())
    .then(data => {
        this.position = data[this.index].position; // 0
        this.symbol = data[this.index].symbol; // H
        this.name = data[this.index].name; // Hydrogen
        this.color = data[this.index].color; // Blue
    });

}

exampleMethod(){

    console.log(this.position); // undefined
    console.log(this.symbol); // undefined
    console.log(this.name); // undefined
    console.log(this.color); // undefined

}

What happens is that in the second .then of the loadData() method, the JSON data is loaded well, but it stays there, and what I want is for it to be stored in the attributes of the constructor How can I do it?

Thanks!

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

0

My suggestion

class Element{

    constructor(){

        this.index = Math.floor(Math.random() * 89);
        this.position;
        this.symbol;
        this.name;
        this.color;
    }

    loadData(data){

        this.position = data.position;
        this.symbol = data.symbol;
        this.name = data.name;
        this.color = data.color;
    }
}

const res = await fetch('./data.json');
const data = await res.json();

const elements = [];
data.forEach(singleData => {
    const singleElement = new Element();
    singleElement.loadData(singleData);
    elements.push(singleElement)
});

console.log(elements);
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