I can't transfer data I get from Fetch to a variable outside of fetch. First variable (currentExam) is an inside object and the seconed one (currentExam2) is an outside json. I want to do it with vanilla JS ( no jQuery)
exams/example.json
[
{
"question": "What time is it",
"options": ["23:04 UTC", "03:44 UTC", "23:04 UTC", "23:04 UTC"],
"answer": 2,
"explain": "",
"image": ""
},
{
"question": "What time is the Sunset?",
"options": ["22:44 UTC", "22:45 UTC", "22:46 UTC ", "06:04 UTC"],
"answer": 4,
"explain": "",
"image": "example.png"
},
{
"question": "What time is it afterwards",
"options": ["23:04 UTC", "03:44 UTC", "23:04 UTC", "23:04 UTC"],
"answer": 2,
"explain": "",
"image": ""
}
]
json-parsing.js
"use strict";
let currentExam = [
{
question: "What time is it",
options: ["23:04 UTC", "03:44 UTC", "23:04 UTC", "23:04 UTC"],
answer: 2,
explain: "",
image: "",
},
{
question: "What time is the Sunset?",
options: ["22:44 UTC", "22:45 UTC", "22:46 UTC ", "06:04 UTC"],
answer: 4,
explain: "",
image: "example.png",
},
];
let currentExam2 = [];
const json_url = "exams/example.json";
fetch(json_url)
.then((response) => response.json())
.then((data) => {
const innerArr = Object.values(data);
currentExam2.push(...innerArr);
});
console.log(currentExam[0]);
console.log(currentExam2[0]);
As I run my code - I get this
{question: 'What time is it', options: Array(4), answer: 2, explain: '', image: ''}
undefined