Build tree array from flat array in javascript Build tree array from flat array in javascript arrays arrays

Build tree array from flat array in javascript


There is an efficient solution if you use a map-lookup. If the parents always come before their children you can merge the two for-loops. It supports multiple roots. It gives an error on dangling branches, but can be modified to ignore them. It doesn't require a 3rd-party library. It's, as far as I can tell, the fastest solution.

function list_to_tree(list) {  var map = {}, node, roots = [], i;    for (i = 0; i < list.length; i += 1) {    map[list[i].id] = i; // initialize the map    list[i].children = []; // initialize the children  }    for (i = 0; i < list.length; i += 1) {    node = list[i];    if (node.parentId !== "0") {      // if you have dangling branches check that map[node.parentId] exists      list[map[node.parentId]].children.push(node);    } else {      roots.push(node);    }  }  return roots;}var entries = [{    "id": "12",    "parentId": "0",    "text": "Man",    "level": "1",    "children": null  },  {    "id": "6",    "parentId": "12",    "text": "Boy",    "level": "2",    "children": null  },  {    "id": "7",    "parentId": "12",    "text": "Other",    "level": "2",    "children": null  },  {    "id": "9",    "parentId": "0",    "text": "Woman",    "level": "1",    "children": null  },  {    "id": "11",    "parentId": "9",    "text": "Girl",    "level": "2",    "children": null  }];console.log(list_to_tree(entries));