Home > Net >  Loop over data and display it in HTML
Loop over data and display it in HTML

Time:09-25

I'm trying to use JavaScript to loop through JSON data that has Parent titles and links and display it in HTML, I've provided below an example of the file structure and how it should look in Html.

var data = {
  "Parent title": [{
    "Link1": "link1.html",
    "Link2": "link2.html",
    "Link3": "link3.html",
  }],
  "Parent title2": [{
    "Link1": "link1.html",
    "Link2": "link2.html",
    "Link3": "link3.html",
  }],
  "Parent 3": [{
    "Link1": "link1.html",
    "Link2": "link2.html",
    "Link3": "link3.html",
  }]
//More and More data
}



<div>
<p>Parent title </p>                         
<ul>
<li><a href="link1.html">Link 1</a></li>
<li><a href="link1.html">Link 2</a></li>
<li><a href="link1.html">Link 3</a></li>
<li><a href="link1.html">Link 4</a></li>
</ul>
<div>

<div>
<p>Parent title 2</p>                         
<ul>
<li><a href="link1.html">Link 1</a></li>
<li><a href="link1.html">Link 2</a></li>
<li><a href="link1.html">Link 3</a></li>
<li><a href="link1.html">Link 4</a></li>
</ul>
<div>
<div>
<p>Parent title 3</p>                         
<ul>
<li><a href="link1.html">Link 1</a></li>
<li><a href="link1.html">Link 2</a></li>
<li><a href="link1.html">Link 3</a></li>
<li><a href="link1.html">Link 4</a></li>
</ul>
<div>

CodePudding user response:

Please don't ask for explicit code, try to ask more specific questions about what you don't understand.

Anyway, this should work:

    // A for...in loop allows you to go over all key-value pairs
    for (const key in data) {
        //We only continue if the field has a value
        if (Object.hasOwnProperty.call(data, key)) {
            const element = data[key];
            const title = document.createElement('p'); //Create a new paragraph
            title.innerText = key; //We want to set the text of the title to the key

            parent.appendChild(title); //Now we can add this to our html file

            //Generate list
            var ul = document.createElement('ul');
            
            //Populate list
            for (const linkTitle in element[0]) {
                if (Object.hasOwnProperty.call(element[0], linkTitle)) {
                    const link = element[0][linkTitle]; //You have key-value pairs in an array with only one element, we get this element
                    //After that, we just create the list item with the link in it
                    li = document.createElement('li');
                    a = document.createElement('a');
                    a.href = link;
                    a.innerText = linkTitle;
                    li.appendChild(a);
                    ul.append(li);
                }
            }
            //Now we can add the populated list to our html file
            parent.appendChild(ul);
        }
    }

And parent is the element where you want to add this content to.

  • Related