[英]How to load JSON data in a JavaScript class properties
我有 JSON 數據如下:
[
{
"position": 0,
"symbol": "H",
"name": "Hydrogen",
"color": "blue"
},
{
"position": 1,
"symbol": "He",
"name": "Helium",
"color": "cyan"
}
]
我想將它加載到 class 屬性中,定義如下:
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;
});
}
}
我想要那個,例如:
constructor(){
this.index = Math.floor(Math.random() * 89);
this.position; // 0
this.symbol; // H
this.name; // Hydrogen
this.color; // Blue
this.loadData();
}
但是會發生以下情況:
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
}
發生的情況是,在 loadData() 方法的 second.then 中,JSON 數據加載得很好,但它仍然存在,我想要將它存儲在構造函數的屬性中我該怎么做?
謝謝!
我的建議
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.