'How to fetch multiple .json files with javascript?
I have multiple .json files and I want to fetch them so I can take information from them. Like user ID, name, salary... I know how to do one, but I need two of them like in const "urls", so I can take data from both of them cycle through It, and put them in HTML elements.
`
const urls = ["./fake-server/employees.json", "./fake-server/salaries.json"];
fetch("./fake-server/salaries.json").then(function (response) {
return response.json();
})
.then(function (data) {
for (var i = 0; i < data.length; i++) {
document.getElementById("data").innerHTML +=
"Person with employee ID of " + "<span class='employee-id'>" + data[i].employeeId + "</span>" + " have salary of " + "<span class='employee-salary'>" + data[i].salary + "</span>" + " $" + " <hr/> ";
}
})
.catch(function (err) {
console.log(err);
});
`
Solution 1:[1]
@Nonik comment's is the way
const urls = ["./fake-server/employees.json", "./fake-server/salaries.json"];
const requests = urls.map(u=>fetch(u));
Promise.all(requests).then(responses => {
responses.forEach(response => {
cost data = response.json();
for (var i = 0; i < data.length; i++) {
document.getElementById("data").innerHTML +=
"Person with employee ID of " + "<span class='employee-id'>" + data[i].employeeId + "</span>" + " have salary of " + "<span class='employee-salary'>" + data[i].salary + "</span>" + " $" + " <hr/> ";
}
});
})
.catch(function (err) {
console.log(err);
});;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | german1311 |