I have the following data structure that's obtained from a third party:

var data = [
    ["Parent1", "Parent1.1", "Parent1.1.1"],
    ["Parent2", "Parent2.1", "Parent2.1.1"],
    ["Parent3", "Parent3.1", "Parent3.1.1"],
    ["Parent1", "Parent1.2", "Parent1.2.1"],
    ["Parent1", "Parent1.2", "Parent1.2.2"]

Where child nodes may or may not be present.
I'm turning it into a tree to represent the data logically:

var tree = {
    "Parent1": {
        "Parent1.1": ["Parent1.1.1"],
        "Parent1.2": ["Parent1.2.1", "Parent1.2.2"]
    "Parent2": {
        "Parent2.1": ["Parent2.1.1"]
    "Parent3": {
        "Parent3.1": ["Parent3.1.1"]

What I'm currently doing seems rather straightforward to myself, but somewhat convoluted due to the numerous return statements:

var tree = data.reduce(function(tree, item) {
    if (!item[0]) return tree;
    tree[item[0]] = tree[item[0]] || {};
    if (!item[1]) return tree;
    tree[item[0]][item[1]] = tree[item[0]][item[1]] || [];
    if (!item[2]) return tree;
    return tree;
}, {}); //Returns as shown above

Is there a better way to approach this problem, what improvements could be made?
The depth of the data is always fixed at three.


1 Answer 1


I was also facing similar issue where I needed to convert the 2-D array to a tree structure. This code might help.:)

var tree = data.reduce(function(tree, item) {
    var tempTree = tree;
    for(var i=0;i<item.length;i++){
            tempTree[item[i]] = {};
        tempTree = tempTree[item[i]];
    return tree;
}, {});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.