Print an Array in <li> line by line with javascript

Asked

Viewed 65 times

3

I need to place the array values inside a list (li), line by line, but the result received brings values in single line.

let x = [
    {
        y: 'Título 1',
        z: ['1' , '2']
    }
];

html = '';

for(let i of x){
    html+= '<h2>' + i.y + '</h2>';
    html+= '<li>' + i.z + '</li>';
  }

document.querySelector('div').innerHTML = html;
<div></div>

2 answers

4

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.

3

Another alternative is to use the DOM HTML which is a structured representation of the document providing methods that allow changing the structure, style and content of the document.

In this case only one iteration was made by the list x and with the aid of the method Document.createElement() DOM elements have been created for HTML [<h2>][3] and <ul>.
Each <h2> has its property Node.innerText configured with the property value y of iterated element.
To the estate z a new iteration is made where for each item of this array an element is created <li> whose property Node.innerText configured with the time item value itself.

With Node.appendChild() the created elements are added to their respective relatives who in turn are added to the document.

let x = [{
    y: 'Título 1',
    z: ['1', '2']
  },
  {
    y: 'Título 2',
    z: ['3', '4']
  }
];

let expositor = document.getElementById("expositor");   //Obtém a referência ao div cujo vai exibir os dados renderizados. 

//Para cada elemento e da lista x...
for (let e of x) {
  let h2 = document.createElement("h2");                //...cria um novo elemento <h2>.
  let ul = document.createElement("ul");                //...cria um novo elemeto <ul>.
  h2.innerText = e.y;                                   //..seta o texto do <h2>.
  //...para cada elemento i de e.z...
  for (let i of e.z) {
    let li = document.createElement("li");              //...cria um <li>.
    li.innerText = i;                                   //...seta o texto do <li>
    ul.appendChild(li);                                 //...apensa o <li> no <ul>
  }
  expositor.appendChild(h2);                            //...apensa <h2> no <div> expositor
  expositor.appendChild(ul);                            //...apensa <ul> no <div> expositor
}
<div id="expositor"></div>

  • 1

    Good, I was going to suggest that too, but I got lazy :-)

  • 1

    @hkotsubo I wrote just because you had not written and I was waiting and did not come....

Browser other questions tagged

You are not signed in. Login or sign up in order to post.