Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Loop through a JSON object and display items as unordered list

i have a fetch that return a json object like this:

{
"id": "xxxxxxxxxxxxxxxxxxx2",
"name": "name",
"instant_invite": "link",
"channels": [
    {
        "id": "xxxxxxxxxxxxxxxxxxx2",
        "name": "Altri Giochi",
        "position": 8
    },
    {
        "id": "xxxxxxxxxxxxxxxxxxx2",
        "name": "Ascolto Musica",
        "position": 11
    },
],
"members": [
    {
        "id": "0",
        "username": "xxxxxxxxxxxxxx",
        "discriminator": "0000",
        "avatar": null,
        "status": "idle",
        "avatar_url": "https://url"
    },
],
"presence_count": 3

}

now i’m trying to map and display all these items to make an unordered list for my website, but i can’t map this object with this.myResponse.map…i get an error "map is not a function".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

i’m definitely lost here and i need some help to make an unordered list that contain all members name, avatar and other stuff.

can someone help me on this in vanilla js?

>Solution :

You can loop through the object using Object.keys(). Here’s an example

let data = {
  "id": "xxxxxxxxxxxxxxxxxxx2",
  "name": "name",
  "instant_invite": "link",
  "channels": [{
      "id": "xxxxxxxxxxxxxxxxxxx2",
      "name": "Altri Giochi",
      "position": 8
    },
    {
      "id": "xxxxxxxxxxxxxxxxxxx2",
      "name": "Ascolto Musica",
      "position": 11
    },
  ],
  "members": [{
    "id": "0",
    "username": "xxxxxxxxxxxxxx",
    "discriminator": "0000",
    "avatar": null,
    "status": "idle",
    "avatar_url": "https://url"
  },
  {
    "id": "1",
    "username": "yyyyyyyyyyyyy",
    "discriminator": "0000",
    "avatar": null,
    "status": "idle",
    "avatar_url": "https://url"
  },],
  "presence_count": 3
}

data.members.forEach(m => {
  // start the UL
  let ul = "<ul class='member'>";
  // loop through using Object.keys(m) or preset array of keys
  ['username','avatar'].forEach(md => {
    ul += `<li>${md}: ${m[md]}</li>`;
  })
  ul += "</ul>";
  document.querySelector('#members').innerHTML += ul;
})
<div id='members'></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading