Tengo datos JSON de la siguiente manera:
[ { "position": 0, "symbol": "H", "name": "Hydrogen", "color": "blue" }, { "position": 1, "symbol": "He", "name": "Helium", "color": "cyan" } ]Y quiero cargarlo en una clase de propiedades definidas de la siguiente manera:
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; }); } }Quiero eso, por ejemplo:
constructor(){ this.index = Math.floor(Math.random() * 89); this.position; // 0 this.symbol; // H this.name; // Hydrogen this.color; // Blue this.loadData(); }Pero lo que sucede es lo siguiente:
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 }Lo que pasa es que en el segundo .then del método loadData() se carga bien el dato JSON, pero se queda ahí, y lo que quiero es que quede guardado en los atributos del constructor ¿Cómo puedo hacerlo?
¡Gracias!
Mi sugerencia
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);