0

I have a list:

var list = ['parent-element', 'child-of-previus-element-1', 'child-of-previus-element-2'];

where each next element in the array is a child of the previous.

I want to transform this list into a tree structure, e.g.:

{
    "parent-element": {
        "childrens": [{
            "child-of-previus-element-1": {
                "childrens": [{
                    "child-of-previus-element-2": {
                        "childrens": []
                    }
                }]
            }
        }]
    }
}

I have tried:

var list = ['parent-element', 'child-of-previus-element-1', 'child-of-previus-element-2'];
var tree = {};

for (var i = 0; i < list.length; i++) {
    if( list[i-1] &&  tree[list[i-1]] ){
      tree[list[i-1]].childrens[list[i]] = {"childrens": []}; 
    } else {
      tree[list[i]] = {
        "childrens": []
      };
    }
}

console.log( JSON.stringify(tree) );

but the output is:

{
    "parent-element":{
        "childrens":[]
     },
     "child-of-previus-element-2":{
        "childrens":[]
     }
}
2
  • 1
    That "treelike structure" is invalid. Commented Jul 25, 2018 at 13:22
  • sorry, fixed... Commented Jul 25, 2018 at 13:25

1 Answer 1

3

You might reduce it right:

var list = ['parent-element', 'child-of-previus-element-1', 'child-of-previus-element-2'];

var tree = list.reduceRight((child, key) => ({ [key]: { children: [child] } }), null);

console.log(JSON.stringify(tree))

Sign up to request clarification or add additional context in comments.

2 Comments

@ar099968 glad to help :)
Good solution, but downplaying other peoples problems with "too easy" feels kinda off..., no offense. (Still upvoted because you solved while I was still thinking about it :) )

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.