JSFiddle - React, Tailwind, and code Playground

by lchau

JavaScript

function shuffle(array) {
  var counter = array.length - 1;
  var tmp;
  var index;
  for (; counter > 0; counter--) {
    index = Math.floor(Math.random() * counter);
    tmp = array[counter];
    array[counter] = array[index];
    array[index] = tmp;
  }
}

function Node(id, parentId, type) {
    return {
        "id": id,
        "parentId": parentId,
        // "isRegion": parentId === null,
        "children": []
    };
}

var list = [
    new Node("A", null, "Property"),
    new Node("B", "A", "Asset"),
    new Node("C", "A", "Building"),
    new Node("D", "C", "Floor"),
    new Node("E", "D", "Room"),
    new Node("F", "D", "Asset"),
    new Node("G", "E", "Asset"),
    new Node("H", "C", "Asset"),
    new Node("A1", null, "Property"),
    new Node("B1", "A1", "Asset"),
    new Node("C1", "A1", "Building"),
    new Node("D1", "C1", "Floor"),
    new Node("E1", "D1", "Room"),
    new Node("F1", "D1", "Asset"),
    new Node("G1", "E1", "Asset"),
    new Node("H1", "C1", "Asset"),
    new Node("I1", "C1", "Asset"),
    new Node("J1", "C1", "Asset")
];
shuffle(list);

var map = {};
var tree = [];

list.forEach(function(o) {
    map[o.id] = o;
});

list.forEach(function(o) {
    var parentId = o.parentId;
    var id = o.id;
    if (parentId === null) {
        tree.push(o);
    } else if (map[parentId]) {
        if (!map[parentId].children) {
            map[parentId].children = [];
        }
        map[parentId].children.push(map[id]);
    }
});

// http://www.jsoneditoronline.org/
console.log(JSON.stringify(tree));