How do I create a nested "list" from JSON data by using template literals?

Viewed 19

I am trying to create a nested "list" using template literals. I have put the word list in quotes because I am not creating an unordered or ordered list, this is just a list of items. This is the data I have.

let items = [{"id":1,"sub":[{"item":2},{"item":4},{"item":2},{"item":8}]},{"id":2,"sub":[{"item":3},{"item":5},{"item":4}]},{"id":3,"sub":[{"item":6},{"item":5},{"item":8}]}];

The result I expect is the following.

<div class="tacos">
   <div>1
      <div>
        <div>2</div>
        <div>4</div>
        <div>2</div>
        <div>8</div>
      </div>
   </div>
   <div>2
        <div>3</div>
        <div>5</div>
        <div>8</div>
   </div>
   <div>3
        <div>6</div>
        <div>5</div>
        <div>8</div>
   </div>
</div>

From here I have the following code in js:

function makeList(items){
   let wrap;
   for (const item of items) {

     wrap += `<div>${item}</div>`;

   }

   return wrap;

}

makeList(items);

From the code above this is what I get:

<div>1</div>
<div>2</div>
<div>3</div>

From this step, I don't know how to get the sub-items. I could make another template, but they are very similar, so I would like to reuse the current template. I have thought about self-referencing, but when I do that for some reason it doesn't work. Any help or guidance will be appreciated.

1 Answers

Just add in an iteration over the .sub property, that returns each of those child <div>s joined by the empty string.

let items = [{"id":1,"sub":[{"item":2},{"item":4},{"item":2},{"item":8}]},{"id":2,"sub":[{"item":3},{"item":5},{"item":4}]},{"id":3,"sub":[{"item":6},{"item":5},{"item":8}]}];

function makeList(items){
   let wrap = '';
   for (const item of items) {
     wrap += `
       <div>
       ${item.id}
       ${item.sub.map(({ item }) => `<div>${item}</div>`).join('')}
       </div>
     `;
   }
   return wrap;
}
console.log(makeList(items));

Related