I'm student and new to JS.
I need help to solve a problem. I have a lot of information so I want to use a static JSON file (json.data) insted of a array. How do I use fetch? I checked some examples but don't understand how to get it work with my code. I would be very thankful for some help, I have been stuck on this for a week.
// Loop through all my properties to display info on page 2
let page2 = (hairdresser) => {
let singleView = "<div>";
for(prop in hairdresser){
if(hairdresser.hasOwnProperty(prop)){
singleView += `${hairdresser[prop]} </p>`;
}
}
singleView += "</div>"
document.body.innerHTML = singleView;
}
// handleData function for page 1
let handleData = (hairdressers) => {
let out = "<table>";
hairdressers.forEach((hairdresser, index) => {
out += "<tr>";
const printableProps = ["time", "name", "price", "timeEst", "rating", "adress"];
printableProps.forEach(prop => {
if (hairdresser.hasOwnProperty(prop)) {
let isName = prop === "name";
out += `<td>
${isName ? `<a href="#" onclick='page2(${JSON.stringify(hairdresser)})'}>` : ""}
${hairdresser[prop]}
${isName ? '</a>' : ""}
</td>`;
}
});
out += "</tr>";
})
out += "</table>";
document.body.innerHTML = out;
}
fetch("/path/to/data.json").then(res => res.json()).then(handleData);
**My JSON file:**
[
{
"name" : "Sax & Fön",
"adress" : "Rådmansgatan 46",
"zip" : "113 57 Stockholm",
"time" : "12",
"tel" : "08-522 389 20",
"site" : "www.salongweb.se",
"rating" : "(32)",
"price" : "320 kr",
"timeEst" : "30 min",
"open" : "Öppet till 19.00 idag",
"desc" : "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris"
},
{
"name" : "Hårley Davidson",
"adress" : "Rådmansgatan 45",
"zip" : "113 57 Stockholm",
"time" : "12",
"tel" : "08-522 389 20",
"site" : "www.salongweb.se",
"rating" : "(32)",
"price" : "320 kr",
"timeEst" : "30 min",
"open" : "Öppet till 19.00 idag",
"desc" : "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris"
}
]
fetchdata? Do you want the JS to read file from your hard drive instead hard coding? JS do not have direct access to local drive unless given permission explicitly. This link may be helpful: stackoverflow.com/questions/7346563/loading-local-json-filedata.jsonfile's contents are identical to what you've posted in thedatavariable above (and that file is available to wherever you're running this JS), that fetch line should work.