DOM content from lists

From ProgZoo
Jump to navigation Jump to search

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