2.0.0 • Published 9 months ago

build-page-tree v2.0.0

Weekly downloads
-
License
ISC
Repository
-
Last release
9 months ago

build-page-tree

buildPageTree(pages)

Transforms an array of page objects into a tree structure.

Parameters

  • pages (Array): An array of page objects. Each object should have the following properties:

    • _id (string): Unique identifier for the page
    • parent_id (string, optional): ID of the parent page
  • pages (Array): An array of page objects. Each object should have the following properties:

    • _id (string): Unique identifier for the page
    • children (Array, optional): Array of child page IDs

Returns

An array of page objects in a tree structure.

Installation

$ npm i build-page-tree

Usage

import {
  buildPageTreeWithParent,
  buildPageTreeWithChildren,
} from "build-page-tree";

const pages1 = [
  { _id: "1", title: "Home" },
  { _id: "2", title: "About", parent_id: "1" },
  { _id: "3", title: "Services", parent_id: "1" },
  { _id: "4", title: "Contact", parent_id: "1" },
  { _id: "5", title: "Web Design", parent_id: "3" },
  { _id: "6", title: "Marron", parent_id: "4" },
];

const pages2 = [
  { _id: "1", title: "Home", children: ["2", "3", "4"] },
  { _id: "2", title: "About", children: [] },
  { _id: "3", title: "Services", children: ["5", "6"] },
  { _id: "4", title: "Contact", children: [] },
  { _id: "5", title: "Web Design", children: [] },
  { _id: "6", title: "SEO", children: [] },
];

const pageTree1 = buildPageTreeWithParent(pages1);
console.log(JSON.stringify(pageTree1, null, 2));

const pageTree2 = buildPageTreeWithChildren(pages2);
console.log(JSON.stringify(pageTree2, null, 2));

Output

[
  {
    "_id": "1",
    "title": "Home",
    "children": [
      {
        "_id": "2",
        "title": "About",
        "parent_id": "1",
        "children": []
      },
      {
        "_id": "3",
        "title": "Services",
        "parent_id": "1",
        "children": [
          {
            "_id": "5",
            "title": "Web Design",
            "parent_id": "3",
            "children": []
          }
        ]
      },
      {
        "_id": "4",
        "title": "Contact",
        "parent_id": "1",
        "children": [
          {
            "_id": "6",
            "title": "Marron",
            "parent_id": "4",
            "children": []
          }
        ]
      }
    ]
  }
]
2.0.0

9 months ago

1.0.3

11 months ago

1.0.2

11 months ago

1.0.1

11 months ago

1.0.0

11 months ago