DOM content from lists
beatles.json
{"members": [ {"firstName":"Paul","lastName":"McCartney"}, {"firstName":"John","lastName":"Lennon"}, {"firstName":"Ringo","lastName":"Starr"}, {"firstName":"George","lastName":"Harrison"} ] }
Using a for loop
- When you have data in a list you can use a for loop to generate content
fetch('/beatles.json') .then((r)=>r.json()) .then((r)=>{ for(let b of r.members){ let div = document.createElement('div'); div.innerHTML = `${b.lastName}, ${b.firstName}`; document.body.append(div); } });
fetch('/beatles.json') .then((r)=>r.json()) .then((r)=>{ for(let beatle of r.members){ let div = document.createElement('div'); div.innerHTML = `${beatle.firstName} ${beatle.lastName}`; document.body.append(div); } });
Using forEach
- An alternative is the forEach method
fetch('/beatles.json') .then((r)=>r.json()) .then((r)=>{ r.members.forEach(b => { let div = document.createElement('div'); div.innerHTML = `${b.lastName}, ${b.firstName}`; document.body.append(div); }) });
fetch('/beatles.json') .then((r)=>r.json()) .then((r)=>{ r.members.forEach(b => { let div = document.createElement('div'); div.innerHTML = `${b.firstName} ${b.lastName}`; document.body.append(div); }) });
Using map
r.albums
is a list, each entry includes a title
and year
- An alternative is the forEach method
fetch('/beatles.json') .then((r)=>r.json()) .then((r)=>{ let lst = r.albums.forEach(a => { let div = document.createElement('div'); div.innerHTML = `${a.title}, ${a.year}`; return div }); document.body.append(lst[0],lst[1],lst[2]); });
fetch('/beatles.json') .then((r)=>r.json()) .then((r)=>{ document.body.append(... r.albums.map(b => { let div = document.createElement('div'); div.innerHTML = `${b.title}, ${b.year}`; return div })); });