Skip to content Skip to sidebar Skip to footer

Create Tree Map In Html Using Json Object

I want to create Treemap using JSON object in which number of children item and and grand-child item will change. My json look like { 'Root': 'Parent', 'Children': {

Solution 1:

You can create recursive function for this, you also need to first check if there is any element in object on any depth that has value of some other type other than object because of result structure.

var json = {"Root":"Parent","Children":{"Children1":{"ChildName":"Child - 1","Children":{"GrandChildren1":{"ChildName":"Grand Child - 1","Children":null},"GrandChildren2":{"ChildName":"Grand Child - 2","Children":null}}},"Children2":{"ChildName":"Child - 2","Children":{"GrandChildren1":{"ChildName":"Grand Child - 1","Children":null},"GrandChildren2":{"ChildName":"Grand Child - 2","Children":null},"GrandChildre3":{"ChildName":"Grand Child - 3","Children":null}}}}}  


var tree = document.querySelector('.tree');

functiontoHTML(data, parent) {
  var check = Object.keys(data).some(function(e) {
    returntypeof data[e] != 'object'
  });
 
  if (check) {
    var ul = document.createElement('ul');
    var li = document.createElement('li')

    for (var i in data) {
      if (typeof data[i] == 'object' && data[i] !== null) {
        toHTML(data[i], li);
      } else {
        var a = document.createElement('a')
        a.textContent = data[i];
        li.appendChild(a);
      }
      ul.appendChild(li);
    }

    parent.appendChild(ul)
  } else {
    for (var i in data) {
      toHTML(data[i], parent)
    }
  }

}

toHTML(json, tree);
<divclass="tree"></div>

Post a Comment for "Create Tree Map In Html Using Json Object"