M
M
Michael2019-10-20 21:40:19
HTML
Michael, 2019-10-20 21:40:19

How to assign html elements values ​​from JSON file?

I have an array of objects in JSON format, which I take by reference.
I need to build a similar system from them (on the left):
disable-tree-menus.gif
In this case, the root element should be an object with Id=-1. All other objects have parents. They need to be arranged in a hierarchical order.
In html, you need to create or assign values ​​to elements from the title attribute of these objects.
That is, it should be something like:

<ul class="treeview">
 <li>Folder 2
    <ul>
        <li>Folder 1</li> //"Folder 1" берется из JSON файла
        <li>Folder 3</li>
    </ul>
  </li>
</ul>

The code. Don't even ask...
$(document).ready(function() {

  $.getJSON('data.json', function(data) {

    const createTree = (data, id, parent, rootParent) => {
      const tree = { [rootParent]: { children: [] } };

      data.forEach(n => tree[n[id]] = { children: [], ...n } );
      data.forEach(n => tree[n[parent]].children.push(tree[n[id]]));

      return tree[rootParent].children;
    };

    const tree = createTree(data, 'id', 'parentId', null);


    var titles = [];
    for(var i =0; i < data.length; i++) {
      titles.push(data[i].title);
    }

    var ul = document.getElementsByClassName('tree')[0];
    var liMassiv = ul.querySelectorAll('li');

    var recurCount = 0;
    var level = 0;

    deep(tree[0]);

    //Рекурсия
    function deep(obj, level) {
      while (obj.children.length > 0) {
        liMassiv[recurCount].textContent = obj.title;
        liMassiv[recurCount].setAttribute('deepLevel', level);
        console.log(liMassiv);
        recurCount++;
        for(var j=0; j<obj.children.length; j++) {
          var n = obj.children[j];
          deep(n, level++);
        }
      }
      console.log(liMassiv[recurCount].textContent);
    }
  });
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stockholm Syndrome, 2019-10-20
@Misha5

const deep = (obj) => {
  const children = obj.children ? `<ul>${obj.children.map(deep).join('')}</ul>` : '';
  return `<li>${obj.title}${children}</li>`;
};

$('.treeview').append(deep(tree[0]));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question