His element i.z
is an array, so if you want each item of it to be separate on its own li
, make another for
to travel it.
Don’t forget to put the li
's within a ul
or ol
. And give better names for variables, because x
, y
and z
are too generic (may seem like a silly detail, but give names better help when programming - as it does not have much context, I gave some names "less generic but not yet ideal"):
let dados = [
{
title: 'Título 1',
items: ['1' , '2']
},
{
title: 'Título 2',
items: ['a' , 'b', 'c']
}
];
let html = '';
for (let element of dados){
html += '<h2>' + element.title + '</h2><ul>';
for (let item of element.items) {
html += '<li>' + item + '</li>';
}
html += '</ul>';
}
document.querySelector('div').innerHTML = html;
<div></div>
You could also join the elements using map
and join
:
let dados = [
{
title: 'Título 1',
items: ['1' , '2']
},
{
title: 'Título 2',
items: ['a' , 'b', 'c']
}
];
let html = '';
for (let element of dados){
html += '<h2>' + element.title + '</h2><ul>';
html += element.items.map(item => '<li>' + item + '</li>').join('');
html += '</ul>';
}
document.querySelector('div').innerHTML = html;
<div></div>
Or even, using two calls from map
(one for the elements of dados
and another for the li
's):
let html = dados
.map((element) => {
return '<h2>' + element.title + '</h2><ul>'
+ element.items.map(item => '<li>' + item + '</li>').join('')
+ '</ul>';
})
.join('');
But in this case I find it an exaggeration. Each call from map
calf another array, but I don’t think it’s necessary to create another array just to join it later, with loops simple you can already put it all together.
Good, I was going to suggest that too, but I got lazy :-)
– hkotsubo
@hkotsubo I wrote just because you had not written and I was waiting and did not come....
– Augusto Vasques