Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
531 views
in Technique[技术] by (71.8m points)

Generate Tree from flat Array javascript

I have an array as follow

arr = [
    {
        id: 1,
        name: 'Node1',
        level: 1
    },
    {
        id: 2,
        name: 'Node2',
        level: 2
    },
    {
        id: 3,
        name: 'Node3',
        level: 3
    },
    {
        id: 4,
        name: 'Node4',
        level: 4
    },
    {
        id: 5,
        name: 'Node5',
        level: 5
    },
];

I want to generate tree on basis of level. Output should be

tree = 
{
    id: 1,
    name: 'Node1',
    level: 1,
    nodes: {
        id: 2,
        name: 'Node2',
        level: 2,
        nodes : {
            id: 3,
            name: 'Node3',
            level: 3,
            nodes: {
                id: 4,
                name: 'Node4',
                level: 4,
                nodes : {
                    id: 5,
                    name: 'Node5',
                    level: 5,
                    nodes: []
                }
            }
        }
    }
}

whenever nodes = [], that means it's the last nodes. the order of array can be anything but tree should be built on basis of level.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use the level property for indicating the nested position in a helper array. Then iterate the data and build children nodes if necessary.

function getTree(array) {
    var levels = [{}];
    array.forEach(function (a) {
        levels.length = a.level;
        levels[a.level - 1].nodes = levels[a.level - 1].nodes || [];
        levels[a.level - 1].nodes.push(a);
        levels[a.level] = a;
    });
    return levels[0].nodes;
}

console.log(getTree([{ id: 1, name: 'Node1', level: 1 }, { id: 2, name: 'Node2', level: 2 }, { id: 3, name: 'Node3', level: 3 }, { id: 4, name: 'Node4', level: 4 }, { id: 5, name: 'Node5', level: 5 }]));
console.log(getTree([{ id: 1, name: 'Node 1', level: 1 }, { id: 2, name: 'Node 1.1', level: 2 }, { id: 3, name: 'Node 1.1.1', level: 3 }, { id: 4, name: 'Node 1.1.1.1', level: 4 }, { id: 5, name: 'Node 1.2', level: 2 }, { id: 6, name: 'Node 1.2.1', level: 3 }, ]));
.as-console-wrapper { max-height: 100% !important; top: 0; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...