javascripttreelodash

Creating a tree from a flat list using lodash


I am trying to create a category tree using the array of json objects below. I want to set a category as a child of another category if its parent equals the id of the other, and I want the posts also to be a children of that category instead of having a separate field for posts, I'll add a flag field that if it is a category or not isParent.

It looks like its working alright, but as you may see, if a category has both category and post as child, it'll only show the categories. Another problem with that is if the post has a null value on its array, it will still push them as children.

What are the mistakes in my code, or is there a simpler or better solution to this?

var tree = unflatten(getData());
var pre = document.createElement('pre');
console.log(tree);
pre.innerText = JSON.stringify(tree, null, 4);

document.body.appendChild(pre);

function unflatten(array, parent, tree) {
  tree = typeof tree !== 'undefined' ? tree : [];
  parent = typeof parent !== 'undefined' ? parent : {
    id: 0
  };
  _.map(array, function(arr) {
    _.set(arr, 'isParent', true);
  });
  var children = _.filter(array, function(child) {
    return child.parent == parent.id;
  });

  if (!_.isEmpty(children)) {
    if (parent.id == 0) {
      tree = children;
    } else {
      parent['children'] = children;
    }
    _.each(children, function(child) {
      var posts = _.map(child.posts, function(post) {
        return _.set(post, 'isParent', false);
      });
      child['children'] = posts;
      delete child.posts;
      unflatten(array, child);
    });
  }

  return tree;

}

function getData() {
  return [{
    "id": "c1",
    "parent": "",
    "name": "foo",
    "posts": [{
      "id": "p1"
    }]
  }, {
    "id": "c2",
    "parent": "1",
    "name": "bar",
    "posts": [{
      "id": "p2"
    }]
  }, {
    "id": "c3",
    "parent": "",
    "name": "bazz",
    "posts": [
      null
    ]
  }, {
    "id": "c4",
    "parent": "3",
    "name": "sna",
    "posts": [{
      "id": "p3"
    }]
  }, {
    "id": "c5",
    "parent": "3",
    "name": "ney",
    "posts": [{
      "id": "p4"
    }]
  }, {
    "id": "c6",
    "parent": "5",
    "name": "tol",
    "posts": [{
      "id": "p5"
    }, {
      "id": "p6"
    }]
  }, {
    "id": "c7",
    "parent": "5",
    "name": "zap",
    "posts": [{
      "id": "p7"
    }, {
      "id": "p8"
    }, {
      "id": "p9"
    }]
  }, {
    "id": "c8",
    "parent": "",
    "name": "quz",
    "posts": [
      null
    ]
  }, {
    "id": "c9",
    "parent": "8",
    "name": "meh",
    "posts": [{
      "id": "p10"
    }, {
      "id": "p11"
    }]
  }, {
    "id": "c10",
    "parent": "8",
    "name": "ror",
    "posts": [{
      "id": "p12"
    }, {
      "id": "p13"
    }]
  }, {
    "id": "c11",
    "parent": "",
    "name": "gig",
    "posts": [{
      "id": "p14"
    }]
  }, {
    "id": "c12",
    "name": "xylo",
    "parent": "",
    "posts": [{
      "id": "p15"
    }]
  }, {
    "id": "c13",
    "parent": "",
    "name": "grr",
    "posts": [{
      "id": "p16"
    }, {
      "id": "p17"
    }, {
      "id": "p14"
    }, {
      "id": "p18"
    }, {
      "id": "p19"
    }, {
      "id": "p20"
    }]
  }]
}
<script src="//cdn.jsdelivr.net/lodash/3.10.1/lodash.min.js"></script>

Expected Output

So the expected output will be more like:

[
   {
       id: 'c1',
       isParent: true,
       children: [
          {
             id: 'c2',
             isParent: true,
             children: []
          },
          {
             id: 'p1'
             isParent: false
          }
       ]
   }
]

And so on..


Solution

  • Your code is very imperative. Try focusing on the "big picture" of data flow instead of writing code by trial-and-error. It's harder, but you get better results (and, in fact, usually it's faster) :)

    My idea is to first group the categories by their parents. This is the first line of my solution and it actually becomes much easier after that.

    _.groupBy and _.keyBy help a lot here:

    function makeCatTree(data) {
        var groupedByParents = _.groupBy(data, 'parent');
        var catsById = _.keyBy(data, 'id');
        _.each(_.omit(groupedByParents, ''), function(children, parentId) {
            catsById['c' + parentId].children = children; 
        });
        _.each(catsById, function(cat) {
            // isParent will be true when there are subcategories (this is not really a good name, btw.)
            cat.isParent = !_.isEmpty(cat.children); 
            // _.compact below is just for removing null posts
            cat.children = _.compact(_.union(cat.children, cat.posts));
            // optionally, you can also delete cat.posts here.
        });
        return groupedByParents[''];
    }
    

    I recommend trying each part in the developer console, then it becomes easy to understand.