A
A
Alexander Sharomet2018-09-25 11:08:35
JavaScript
Alexander Sharomet, 2018-09-25 11:08:35

How to output data object to ul list using recursive function?

How to output data from an array to a multilevel ul list?
There is an array:

const data = [
  {"name": "item 1"},
  {"name": "item 2"},
  {
    "name": "item 3",
    "children": [
      {
        "name": "sub item 1",
        "children": [{
          "name": "sub sub item 1",
        }]
      },
      {"name": "sub item 2"},
      {"name": "sub item 3"},
      {"name": "sub item 4"}
    ]
  },
  {"name": "item 4"}
];

And it needs to be listed like this:
<ul>
      <li>item 1</li>
      <li>item 2</li>
      <li>item 3
        <ul>
          <li>sub item 1
            <ul>
              <li>sub sub item 1</li>
            </ul>
          </li>
          <li>sub item 2</li>
          <li>sub item 3</li>
          <li>sub item 4</li>
        </ul>
      </li>
      <li>item 4</li>
    </ul>


I tried to create a recursive function but got confused:
Example
const data = [ //Массив с данными
  {"name": "item 1"},
  {"name": "item 2"},
  {
    "name": "item 3",
    "children": [
      {
        "name": "sub item 1",
        "children": [{
          "name": "sub sub item 1",
        }]
      },
      {"name": "sub item 2"},
      {"name": "sub item 3"},
      {"name": "sub item 4"}
    ]
  },
  {"name": "item 4"}
];

let ul = document.createElement('ul'); // Создаём ul элемент
let main = document.querySelector('#mainContent').appendChild(ul); // Вставляем его в #mainContent

createTree(data); // Вызываем функцию и передаём в нее массив с данными

function createTree(dat) {  
  dat.map(item => {
    if(item.children) { // Если элемент имеет children
      main.innerHTML += '<li>'+item.name+'</li>'; // Вставляем имя элемента
      let subItem = document.createElement('ul'); // Создаём новый элемент ul
      main = main.appendChild(subItem);
      main.innerHTML += createTree(item.children);      
    }
    main.innerHTML += '<li>'+item.name+'</li>';
    
  });
}


How to implement it correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-09-25
@sharomet

function createTree(data) {
  const ul = document.createElement('ul');

  data.forEach(item => {
    const li = document.createElement('li');
    li.textContent = item.name;

    if (item.children) {
      li.appendChild(createTree(item.children));
    }

    ul.appendChild(li);
  });

  return ul;
}


document.querySelector('#mainContent').appendChild(createTree(data));

or
const createTree = (data) => `
  <ul>${data.map(n => `
    <li>
      ${n.name}
      ${n.children ? createTree(n.children) : ''}
    </li>`).join('')}
  </ul>`;


document.querySelector('#mainContent').innerHTML = createTree(data);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question