JSFiddle - React, Tailwind, and code Playground

by jonahe

JavaScript

var arr = [
  {'id':1 ,'parentid' : 0},
  {'id':2 ,'parentid' : 1},
  {'id':3 ,'parentid' : 1},
  {'id':4 ,'parentid' : 2},
  {'id':5 ,'parentid' : 0},
  {'id':6 ,'parentid' : 0},
  {'id':7 ,'parentid' : 4}
];

function unflatten(array, parent, tree) {

  tree = typeof tree !== 'undefined' ? tree : [];
  parent = typeof parent !== 'undefined' ? parent : { id: 0 };

  var children = array.filter(function(child){ return child.parentid === parent.id; });

  if (children.length) {
    if (!parent.id) {
      tree = children;
    }else{
      parent['children'] = children;
    }
    children.forEach(function(child){ unflatten( array, child ) } );                    
  }

  return tree;
}

tree = unflatten( arr );
document.body.innerHTML = "<pre>" + (JSON.stringify(tree, null, " "))