DenQ / list-to-tree

Convert list to tree
BSD 3-Clause "New" or "Revised" License
87 stars 30 forks source link
algorithm algorithm-library converter data-structures datastructures help-tools list-to-tree tools tree tree-structure trees

list-to-tree

This lib is help-tool for convertation list to tree a data structure.

Attention

  • Recently I have rewritten the project and now it is based on IronTree - it allowed to do the project in unix way style and added flexibility. IronTree has a fairly rich interface.
  • The tree can now be sorted - you only need to pass your sorting method if you are not satisfied with the native sorting.

Install on npm

npm install list-to-tree --save

Usage

    var LTT = require('list-to-tree');
    var list = [
    {
        id: 1,
        parent: 0
    }, {
        id: 2,
        parent: 1
    }, {
        id: 3,
        parent: 1
    }, {
        id: 4,
        parent: 2
    }, {
        id: 5,
        parent: 2
    }, {
        id: 6,
        parent: 0
    }, {
        id: 7,
        parent: 0
    }, {
        id: 8,
        parent: 7
    }, {
        id: 9,
        parent: 8
    }, {
        id: 10,
        parent: 0
    }
    ];

    var ltt = new LTT(list, {
        key_id: 'id',
        key_parent: 'parent'
    });
    var tree = ltt.GetTree();

    console.log( tree );
Result
[{
    "id": 1,
    "parent": 0,
    "child": [
        {
            "id": 2,
            "parent": 1,
            "child": [
                {
                    "id": 4,
                    "parent": 2
                }, {
                    "id": 5,
                    "parent": 2
                }
            ]
        },
        {
            "id": 3,
            "parent": 1
        }
    ]
}, {
    "id": 6,
    "parent": 0
}, {
    "id": 7,
    "parent": 0,
    "child": [
        {
            "id": 8,
            "parent": 7,
            "child": [
                {
                    "id": 9,
                    "parent": 8
                }
            ]
        }
    ]
}, {
    "id": 10,
    "parent": 0
}];

Properties

Methods

Testing

For run testing, typing on your console

npm test