Create a nested array recursively

Any suggestions for recursively creating a set of nested arrays / objects?

I allow my users to add multiple items using a quick text box. They will indicate auxiliary elements 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 problem is that I don’t know the depth to which the nodes will go down.

Any suggestions would be greatly appreciated.

+4
source share
1 answer

This is a linear approach without recursion.

You can count the stars and take this information for the desired level of a given node.

.

, .

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; }
Hide result
+3

Source: https://habr.com/ru/post/1689880/


All Articles