@valcosmos/to-tree
TypeScript icon, indicating that this package has built-in type declarations

0.0.6 • Public • Published

@valcosmos/to-tree

Introduction

  • 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.

Installation

use npm:

npm i @valcosmos/to-tree

use yarn:

yarn add @valcosmos/to-tree

use pnpm:

pnpm add @valcosmos/to-tree

Usage

/**
 *
 * @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')

Development

clone locally:

git clone https://github.com/valcosmos/toTree.git

cd toTree

yarn

yarn test

Package Sidebar

Install

npm i @valcosmos/to-tree

Weekly Downloads

1

Version

0.0.6

License

MIT

Unpacked Size

5.81 kB

Total Files

5

Last publish

Collaborators

  • valcosmos