wittenator
wittenator

Reputation: 23

Transforming tree recursively in JS/ES6

I am currently trying to transform a tree, given by in this form:

{"Parent": 
    {
    "Child1": ["toy1"],
    "Child2": 
          {
              "Nephew": ["toy2", "toy3"]
          }
    }
}


into a tree of the following form:

{
"name": "root",
"children": 
    [{"name":"Parent",
      "children": 
          [{
          "name":"Child1",
          "children": ["toy1"]
          },
          {
          "name":"Child2"
          "children": 
              [{
              "name":"Nephew",
              "children": ["toy2", "toy3"]
              }]
          }]
    }]
}


So basically I want to standardize the structure of the tree. I tried that with the following code:

function recurse(elem) {
    if (typeof(elem) !== "object") return elem;
    level = [];
    for (let part in elem) {
        level.push({
            name: part,
            children: recurse(elem[part])
        });
        console.log(level);
    }
    return level;
}
restrucTree = {
    name: "root",
    children: recurse(tree)
};

But that apparently there are some errors concerning the correct recursion and building of the object since the root node (in this case "Parent") isn't included in the transformed tree. Furthermore this method fails if the tree branches in several sub-trees. In this case just the last one gets recognized. My best guess is that ,while popping the stack of the recursion, stored objects get lost, but somehow I can't translate that to a solution. If you have any idea, where this error comes from, I would be very grateful!

Upvotes: 2

Views: 1070

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386578

You could take a recursive approach and iterate all keys and build new objects and take either the array or take the object for the next recursive call.

function getParts(object) {
    return Array.isArray(object)
        ? object
        : Object.keys(object).map(function (k) {
            return { name: k, children: getParts(object[k]) };
        });
}

var data = { Parent: { Child1: ["toy1"], Child2: { Nephew: ["toy2", "toy3"] } } },
    result = { name: 'root', children: getParts(data) };

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Related Questions