Djoko_de_loco
Djoko_de_loco

Reputation: 13

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

`

Upvotes: 0

Views: 2653

Answers (1)

german1311
german1311

Reputation: 93

@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);
});;
    

Upvotes: 2

Related Questions