Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

129
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda