- A tool for converting flattened array into tree.
- I made this by TypeScript.
- If you like it, you can give a star on github
- If you get some issues, welcome to submit issues on github.
use npm:
npm i @valcosmos/to-tree
use yarn:
yarn add @valcosmos/to-tree
use pnpm:
pnpm add @valcosmos/to-tree
/**
*
* @param data ==>[required] the data what you want to converted to tree
* @param key ==>[optional] the unique key in the data
* @param parentKey ==>[optional] the unique key of the parent node in the data
* @returns
*/
import { toTree } from '@valcosmos/to-tree'
const arr = [
{ id: 1, title: '1', pid: 0 },
{ id: 2, title: '2', pid: 1 },
{ id: 3, title: '3', pid: 2 }
]
// use it to convert, and you will get what you want
const res = toTree(arr)
Maybe you don't have field for id and pid in your data. And this time you can reset the fields you want.
You just need to pass two parameters in the toTree.
import { toTree } from '@valcosmos/to-tree'
const arr = [
{ _id: 1, title: '1', parentId: 0 },
{ _id: 2, title: '2', parentId: 1 },
{ _id: 3, title: '3', parentId: 2 }
]
// use it to convert, and you will get what you want
const res = toTree(arr, '_id', 'parentId')
clone locally:
git clone https://github.com/valcosmos/toTree.git
cd toTree
yarn
yarn test