Introducing Socket Firewall: Free, Proactive Protection for Your Software Supply Chain.Learn More
Socket
Book a DemoInstallSign in
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

latest
npmnpm
Version
1.0.1
Version published
Weekly downloads
241
100.83%
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 30 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