1.0.1 • Published 4 years ago

tree-with-array v1.0.1

Weekly downloads
43
License
MIT
Repository
github
Last release
4 years ago

tree-with-array

Conversion between tree data and array data

Install

npm i tree-with-array

Usage

arrayToTree

const { arrayToTree } = require('tree-with-array');
const list = [
  {
    id: '0'
  },
  {
    id: '0-1',
    parentId: '0'
  },
  {
    id: '0-1-1',
    parentId: '0-1'
  },
  {
    id: '0-2',
    parentId: '0'
  },
  {
    id: '1'
  }
];
const tree = arrayToTree(list);
console.log(tree);
/*
  [
    {
      id: '0',
      children: [
        {
          id: '0-1',
          parentId: '0',
          children: [
            {
              id: '0-1-1',
              parentId: '0-1'
            }
          ]
        },
        {
          id: '0-2',
          parentId: '0'
        }
      ]
    },
    {
      id: '1'
    }
  ];
*/

treeToArray

const { treeToArray } = require('tree-with-array');
const tree = [
  {
    id: '0',
    children: [
      {
        id: '0-1',
        children: [
          {
            id: '0-1-1'
          }
        ]
      },
      {
        id: '0-2'
      }
    ]
  },
  {
    id: '1'
  }
];
const list = treeToArray(tree);
console.log(list);
/* 
  [
    {
      id: '0',
      children: [
        {
          id: '0-1',
          children: [
            {
              id: '0-1-1'
            }
          ]
        },
        {
          id: '0-2'
        }
      ]
    },
    {
      id: '0-1',
      children: [
        {
          id: '0-1-1'
        }
      ]
    },
    {
      id: '0-1-1'
    },
    {
      id: '0-2'
    },
    {
      id: '1'
    }
  ];
 */

Api

arrayToTree(list, [options])

arrayToTree(list, {
  idKey,
  pIdKey
  // ...
});

options

namedescriptiontypeaccepted valuesdefault
idKeythe node's attribute to save node's unique identifier.support chain calls.stringid
pIdKeythe node's attribute to save its parent node's unique identifier.support chain calls.stringparentId
isKeyChainwhether to enable the chain call of idKey and pIdKeybooleantrue
detachedwhether to preserve the node which specifies parent's identifier but the parent node is non-existent.if set true, the node keep as root node.if set false, the node will be abandoned and output error message to console.booleantrue
sortKeythe node's attribute to save node's sort value.string''
orderspecify the sort type.works when sortKey is specified.stringascending/descendingascending
traversetraverse all nodes.parent is null when it has no parent.function(node, parent) => {}

treeToArray(tree, [options])

treeToArray(tree, {
  childrenKey
});

options

namedescriptiontypeaccepted valuesdefault
childrenKeyspecify which node attribute is used as the node's subtreestringchildren

Test

npm run test

License

MIT