Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@valu/trees

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@valu/trees

Javascript/TypeScript utility to turn WordPress like flat list (child -> parent relation) of hierarchical items to a tree data structure

  • 1.0.0
  • npm
  • Socket score

Version published
Weekly downloads
49
decreased by-55.86%
Maintainers
1
Weekly downloads
 
Created
Source

@valu/trees

Javascript/TypeScript utility to turn WordPress like flat list (child -> parent relation) of hierarchical items to a tree data structure.

Install

npm install @valu/trees

Example:

import { flatListToTrees } from "@valu/trees";

const list = [
    {
        name: "Parent",
        id: 1,
        parent: 0,
    },
    {
        name: "Child 1",
        id: 2,
        parent: 1,
    },
    {
        name: "Child 2",
        id: 3,
        parent: 1,
    },
    {
        name: "Grandchild",
        id: 4,
        parent: 3,
    },
];

const trees = flatListToTrees(list, {
    getId: (item) => item.id,
    getParentId: (item) => item.parent,
});

will yield trees as

[
    {
        node: { name: "Parent", id: 1, parent: 0 },
        children: [
            { node: { name: "Child 1", id: 2, parent: 1 }, children: [] },
            {
                node: { name: "Child 2", id: 3, parent: 1 },
                children: [
                    {
                        node: { name: "Grandchild", id: 4, parent: 3 },
                        children: [],
                    },
                ],
            },
        ],
    },
];

This makes it easy to build recursive menu tree components in React

function MenuTree(props: { trees: typeof trees }) {
    return (
        <div>
            {props.trees.map((tree) => (
                <div style={{ marginLeft: "1rem" }}>
                    <div>{tree.node.name}</div>
                    <MenuTree trees={tree.children} />
                </div>
            ))}
        </div>
    );
}

which will render roughly to:

Parent
    Child 1
    Child 2
        Grandchild

FAQs

Package last updated on 29 Jul 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc