Giter Club home page Giter Club logo

list-to-tree's Introduction

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

  • tree - This property is IronTree type and have methods: add, remove, contains, sort, move, traversal, toJson, etc...
  • options
    • key_id (string) Field name for id item. Default: 'id'.
    • key_parent (string) Field name for parent id. Default: 'parent'.
    • key_child (string) Field name for children of item. Default 'child'.
    • empty_children (boolean) Flag for allow empty children property in item. Default: false.

Methods

  • constructor(list, options)
    • params:
      • list - array list with elements. Like { id: 5: parent: 1 }.
      • options - optional parameter. Object for describe flags and field names for tree.
  • .GetTree() This method will be return json tree
    • example:
        tree.GetTree()
      
  • .sort(callback) The custom sort method
    • callback(a, b) - a and b have IronTree\Node type and have methods: add, remove, get, set, sort, traversal, etc...
    • example:
      function compareById(vector) {
        return (a, b) => {
          const aid = Number(a.get('id'));
          const bid = Number(b.get('id'));
          if (aid > bid) {
            return vector ? 1 : -1;
          } else if (aid < bid) {
            return vector ? -1 : 1;
          } else {
            return 0
          }
        };
      }
      ltt.sort(compareById(false));

Testing

For run testing, typing on your console

npm test

list-to-tree's People

Contributors

denq avatar grant avatar hyber1z0r avatar jesusisao avatar mucholucho avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

list-to-tree's Issues

Feature: need sort

Sometime, we need an order_key to sort the tree.
Could we add this feature?

Sorting Fails on Negative Id Keys

Hi, This library works well with my list except that it rearrange some records with negative IDs and puts them at the beginning instead of their normal location.

Is there a way around it ?

License

License

I recommend add license to the people can use the package in commercial projects too

is there any limit on the depth level or the number of children in the tree?

I am facing some issues while parsing the tree; where in the big tree it does not parse the node appropriately. but When I test with only that specific sub tree it works okay.

I am getting below warnings for all the missing nodes in the tree. This might be helpful for you.
Warning
tree.js:42
RowDataPacket { id: 24834, name: "Loans for vehicle - interest component", category_id: "Loa556", parent_id: 24904, โ€ฆ}
tree.js:42

Consider dynamic parent/child matching fn()

return parentNode.get(key_id) === item[key_parent];

I have a need to generate a tree from a collection (array of objects). But my paths are nested - eg:

{
  id: 100,
  field: 'val',
  // ... 
  meta: {
    parent: 'abc-123'
  }
}

I need to either pass dot-notation paths (and use a third party lib, like _ or object-path) or, to avoid dependencies, perhaps consider passing a matching fn to the constructor, which I can use third party libs without affecting deps on this module.

// list-to-tree constructor - add new param to end
 constructor(list, options = {}, matcher) {
    const _list = list.map((item) => item);

    options = Object.assign({}, defaultOptions, options);
    this.options = options;
    const { key_id, key_parent } = options;

    sortBy(_list, key_parent, key_id);
    const tree = new IronTree({ [key_id]: 0 });
    _list.forEach((item, index) => {
      tree.add((parentNode) => {
       // crude example below:
        return matcher ? matcher(item, key_id, parentNode, key_parent) : parentNode.get(key_id) === item[key_parent];
      }, item);
    });

    this.tree = tree;
  }

Then you could pass whatever id-to-id matching fns you need.

// my application code
const objectPath = require('object-path')
matcher = function (item, key_id, parentNode, key_parent) {
  return objectPath.get(parentNode, key_id) === objectPath.get(item, key_parent)
}

Now I can use:

new Tree(list, {
  key_id: 'id',
  key_parent: 'meta.parent'
}, matcher)

Thoughts?

Does not work with strings as key_id and key_parent?

It seems, links / references do not work with string values.
Is this on purpose? Are there are some reasons?

`const list = [
{
_id: "EL",
parentId: 0
}, {
_id: 2,
parentId: "EL"
}, {
_id: 3,
parentId: "EL"
}
];

getTree() {
const llt = new LLT(list, {
key_id: '_id',
key_parent: 'parentId'
});
return llt.GetTree();
}`

Lib just gives warnings:
2018-06-22_165825

Child key must be bigger than parent key

Problem

When the child's ID is smaller than the parent's ID, the child may not be associated properly.
The reason is that there is code that sorts by parent ID, then sorts by ID, and adds to the tree.

example

before

PR

I think you can solve this problem by sorting the list by the depth of the tree.

Here is a suggestion:
#26

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.