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!
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);