d-forest
A lightweight JavaScript library for searching object in a tree-like structure.
Install
npm install d-forest --save
Usage
const df = require('d-forest');
const data = {
c1: { name: 'category1', active: false },
c2: {
name: 'category2',
active: true,
products: {
p1: { name: 'product21', active: false },
p2: { name: 'product22', active: true },
p3: { name: 'product23', active: false },
},
},
c3: {
name: 'category3',
active: true,
products: {
p1: { name: 'product31', active: false },
p2: { name: 'product32', active: true },
},
},
};
df.findNode(data, (node) => node.name === 'category3');
df.findLeaf(data, (leaf) => leaf.name === 'product22');
Methods
-
findNode | findLeaf
-
findNodes | findLeaves
-
forEachNode | forEachLeaf
-
mapLeaves
let level = df.maxHeight(data) - 1;
df.mapLeaves(data, (leaf) => leaf.name, level);
df.everyNode(data, (node) => node.hasOwnProperty('active'));
df.everyLeaf(data, (leaf) => leaf.hasOwnProperty('active'));
df.minHeight(data);
df.maxHeight(data);
df.nodesByLevel(data, 1);
df.reduce(data, (acc, cur) => (cur.name ? `${acc}/${cur.name}` : acc), '');
const nodes = df.hierarchy(data, (node) => node.name === 'product31');
nodes.map((node) => node.name).filter(Boolean);
df.findLevel(data, (node) => node.name === 'category2');
df.findLevel(data, (node) => node.name === 'product21');
df.findPath(data, (node) => node.name === 'product22');
df.findByPath(data, ['c2', 'products', 'p2']);
Following methods don't mutate data, instead return new one with shared mutable state.
-
removeByPath
-
removeNodes | removeLeaves
df.removeLeaves(data, (leaf) => leaf.active === false);
-
updateByPath
-
updateNodes | updateLeaves
df.updateNodes(
data,
(node, depth) => depth === 1 && node.active,
(node) => ({ ...node, products: null })
);
df.removeByLevel(data, 2);