项目作者: sfengyuan

项目描述 :
Convert array to tree structure.
高级语言: HTML
项目地址: git://github.com/sfengyuan/array-tree-converter.git
创建时间: 2020-02-18T06:08:00Z
项目社区:https://github.com/sfengyuan/array-tree-converter

开源协议:

下载


arrayTreeConverter

Converts a flat array of objects to a tree structure.

Example

Input:

  1. [{
  2. id: 6,
  3. any: 'titi'
  4. }, {
  5. id: 2,
  6. pid: 5,
  7. any: 'bar',
  8. }, {
  9. id: 1,
  10. pid: 2,
  11. any: 'foo'
  12. }, {
  13. id: 5,
  14. any: 'quox'
  15. }, {
  16. id: 3,
  17. pid: 2,
  18. any: 'baz'
  19. }
  20. ]

Output:

  1. [{
  2. id: 6,
  3. any: 'titi',
  4. children: []
  5. }, {
  6. id: 5,
  7. any: 'quox',
  8. children: [{
  9. id: 2,
  10. pid: 5,
  11. any: 'bar',
  12. children: [{
  13. id: 1,
  14. pid: 2,
  15. any: 'foo',
  16. children: []
  17. }, {
  18. id: 3,
  19. pid: 2,
  20. any: 'baz',
  21. children: []
  22. }]
  23. }]
  24. }
  25. ]

Usage

Install

  1. npm install array-tree-converter
  2. //or
  3. <script src="https://unpkg.com/array-tree-converter@1.0.1/dist/web/index.js"></script>
  1. arrayTreeConverter(input, {
  2. ID_KEY: 'name',
  3. PARENT_KEY: 'parent',
  4. CHILDREN_KEY: 'children'
  5. })
  6. arrayTreeConverter(input)

API

  1. arrayTreeConverter(input, {
  2. ID_KEY: itemIdOfInput, // default: id
  3. PARENT_KEY: itemParentIdOfInput, // default: pid
  4. CHILDREN_KEY: itemChildrenIdOfOutput // default: children
  5. })

LICENSE

MIT