Recursively create a nested array

Viewed 598

Any suggestions for how to recursively create a set of nested arrays / objects?

I am letting my users add multiple elements using a quick textarea. They will indicate sub items with an asterisk. So I have a string like this that I want to turn into an array.

level 1.1
level 1.2
* level 1.2.1
** level 1.2.1.1
** level 1.2.1.2
* level 1.2.2

This is the result I would like to see:

[
    {
        name: "level 1.1"
    },
    {
        name: "level 1.2",
        nodes: [
            {
                name: "level 1.2.1",
                nodes: [
                    {
                        name: "level 1.2.1.1"
                    },
                    {
                        name: "level 1.2.1.2"
                    }
                ]
            },
            {
                name: "level 1.2.2"
            }
        ]
    }
]

The challenge is that I don't know the depth that the nodes will go down to.

Any suggestions would be gratefully received.

1 Answers

This is a linear approach, without recursion.

You could count the stars and take this information for the wanted level of the given node.

This proposal uses an array as reference to the last inserted level and maintains the wanted object structure.

This solution does not provide sanity checks, if a level is missing.

var data = ['level 1.1', 'level 1.2', '* level 1.2.1', '** level 1.2.1.1', '** level 1.2.1.2', '* level 1.2.2'],
    result = [],
    levels = [{ nodes: result }];

data.forEach(function (s) {
    var level = (s.match(/^\*+(?=\slevel)/) || [''])[0].length,
        name = s.match(/[^*]+$/)[0].trim();

    levels[level].nodes = levels[level].nodes || [];
    levels[level].nodes.push(levels[level + 1] = { name: name });
});

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

Related