2.1.0-b • Published 4 months ago

row-to-tree v2.1.0-b

Weekly downloads
-
License
MIT
Repository
github
Last release
4 months ago

row-to-tree

Version Test Version

Converts an array of objects into a tree structure. If you want to test it, go to the demo!

Why?

When you make a SQL request, you often get an array of rows, each of them being linked to another one in a parent/child relation. And you may want to use this array to display a tree, for example in a Vuetify component.

This module helps you convert the original array into an array of parents and child, building the expected tree:

Expected output

Example

The test file provides an example of what could be done. Suppose you have the following table:

idid_parentname
1nullROOT
21LEAF 2
41LEAF SISTER
62OTHER LEAF
5nullNEW ROOT

You will end up with an array of objects,

How?

Installation

npm install --save row-to-tree

Usage

const { rowToTree } = require("row-to-tree");

const data = [
  { id: 1, id_parent: null, name: "ROOT" },
  { id: 2, id_parent: 1, name: "LEAF 2" },
  { id: 4, id_parent: 1, name: "LEAF SISTER" },
  { id: 6, id_parent: 2, name: "OTHER LEAF" },
  { id: 5, id_parent: null, name: "NEW ROOT" },
];

console.log(rowToTree(data));

You will get this nested array:

[
  {
    id: 1,
    id_parent: null,
    name: "ROOT",
    children: [
      {
        id: 2,
        id_parent: 1,
        name: "LEAF 2",
        children: [
          {
            id: 6,
            id_parent: 2,
            name: "OTHER LEAF",
            children: [],
          },
        ],
      },
      {
        id: 4,
        id_parent: 1,
        name: "LEAF SISTER",
        children: [],
      },
    ],
  },
  {
    id: 5,
    id_parent: null,
    name: "NEW ROOT",
    children: [],
  },
];

API

rowToTree(data, options)

Convert an array of objects into a tree structure: returns an array of root objects.

Licence

MIT

2.1.0-a

5 months ago

2.1.0-b

4 months ago

2.1.0

5 months ago

2.0.1

10 months ago

2.0.0

10 months ago

1.0.1

1 year ago

1.0.0

1 year ago