[英]How do I create a nested "list" from JSON data by using template literals?
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:从这里我在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.任何帮助或指导将不胜感激。
Just add in an iteration over the .sub
property, that returns each of those child <div>
s joined by the empty string.只需在.sub
属性上添加一个迭代,它返回由空字符串连接的每个子<div>
。
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.