0

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

`

2
  • for (let url of urls) { fetch(url).then(...) } Commented May 13, 2022 at 16:36
  • you can do map on url array and within map can do fetch, make sure to wrap it in promise all Commented May 13, 2022 at 16:38

1 Answer 1

2

@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);
});;
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.