Teguh Santoso
Teguh Santoso

Reputation: 13

Convert Flatten Array to Parent Child Array Without any Parent Information

I have a problem for converting flatten array to tree node/parent child formatted array, I have thought using recursive solution but I still don't know how to Implement it. the best thing could be useful for grouping the list its only manipulating string code from the object item. like 01.05 || 01.05.011 || 01.05.011.0001|| 01.05.011.0002|| 01.05.011.0003 my goal is just want to convert those code became like this:

{
  code: 01,
  child: [
     code : 05,
       child: [{
          code: 011,
          child: [
             {
               code: 0001,
               child:[]
             },
             {
               code: 0002,
               child:[]
             },
              {
               code: 0003,
               child:[]
             }
           ]
       }]
  ]
}

How do I solve this problem?

Upvotes: 1

Views: 235

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386736

You could split the strings by the dot and take each part as new level for a nested structure.

var array = ['01.05', '01.05.011', '01.05.011.0001', '01.05.011.0002', '01.05.011.0003'],
    result = array.reduce((r, s) => {
        s
            .split('.')
            .reduce((children, code) => {
                var temp = children.find(o => o.code === code);
                if (!temp) children.push(temp = { code, children: [] });
                return temp.children;
            }, r);
        return r;
    }, []);

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

Upvotes: 1

Related Questions