Difference between revisions of "DOM content from lists"

From ProgZoo
Jump to navigation Jump to search
Line 65: Line 65:
   });
   });


</pre>
</div>
== Using map ==
<div class=qu>
<code>r.albums</code> is a list, each entry includes a <code>title</code> and <code>year</code>
*An alternative is the forEach method
<pre class=usr>
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]);
  });
</pre>
<pre class=ans>
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
    }));
  });
</pre>
</pre>
</div>
</div>

Revision as of 15:14, 27 August 2021


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