
Security News
PodRocket Podcast: Inside the Recent npm Supply Chain Attacks
Socket CEO Feross Aboukhadijeh discusses the recent npm supply chain attacks on PodRocket, covering novel attack vectors and how developers can protect themselves.
@dqcai/tree
Advanced tools
A TypeScript library for converting arrays to tree structures and vice versa
Transform database arrays into hierarchical tree structures with powerful TypeScript support - Move business logic from backend to frontend effortlessly!
@dqcai/tree is a revolutionary TypeScript/JavaScript library designed to bridge the gap between database flat structures and frontend tree hierarchies. Perfect for modern application architecture where you want to shift business logic processing from server-side to client-side.
Database → Complex SQL Queries → Backend Processing → API → Frontend Display
Database → Simple Flat Array → API → @dqcai/tree → Rich Frontend Experience
# NPM
npm install @dqcai/tree
# Yarn
yarn add @dqcai/tree
# PNPM
pnpm add @dqcai/tree
Transform database query results into nested tree structures:
import { Array2Tree } from '@dqcai/tree';
const converter = new Array2Tree();
// Your database query results (flat array)
const databaseResults = [
{ id: 1, parent_id: null, name: 'Root Department', budget: 100000 },
{ id: 2, parent_id: 1, name: 'IT Department', budget: 50000 },
{ id: 3, parent_id: 1, name: 'HR Department', budget: 30000 },
{ id: 4, parent_id: 2, name: 'Development Team', budget: 35000 },
{ id: 5, parent_id: 2, name: 'DevOps Team', budget: 15000 }
];
// Convert to nested tree structure
const treeStructure = converter.array2Tree(databaseResults, 'id', 'parent_id');
console.log(treeStructure);
// Result: Nested objects with $children arrays, $level properties
Perfect for hierarchical reports and organizational charts:
// Sort flat array in hierarchical order (like Oracle's CONNECT BY)
const hierarchicalSort = converter.array2SortByTree(databaseResults, 'id', 'parent_id');
console.log(hierarchicalSort);
// Result: Flat array sorted in tree order with $level, $index, $tree_index
Ideal for budget allocation, KPI calculations, and weighted hierarchies:
const budgetData = [
{ id: 1, parent_id: null, department: 'Company', budget: 1000000 },
{ id: 2, parent_id: 1, department: 'Engineering', budget: 600000 },
{ id: 3, parent_id: 1, department: 'Marketing', budget: 400000 },
{ id: 4, parent_id: 2, department: 'Frontend', budget: 300000 },
{ id: 5, parent_id: 2, department: 'Backend', budget: 300000 }
];
// Calculate weights and percentages from leaf to root
const weightedTree = converter.array2SortAndWeight(
budgetData, 'id', 'parent_id', 'budget'
);
// Each node now has: $weight_percent, $root_weight_percent, $parent_weight_percent
console.log(weightedTree);
Convert complex tree structures back to flat database-ready arrays:
const complexTree = [
{
name: 'Root',
children: [
{ name: 'Child 1', children: [{ name: 'Grandchild 1' }] },
{ name: 'Child 2' }
]
}
];
// Convert tree back to flat array with auto-generated IDs
const flatArray = converter.tree2Array(complexTree, 'children');
// Result: Flat array with $id, $parent_id for database insertion
array2Tree(data, idKey, parentKey, startWith?, level?)
Purpose: Convert flat array to nested tree with $children
property
Parameters:
data
: Array of objects with parent-child relationshipsidKey
: Primary key field name (e.g., 'id')parentKey
: Foreign key field name (e.g., 'parent_id')startWith
: Root value to start tree building (default: null)level
: Starting level number (default: 1)Returns: Nested tree array with $children
, $level
, $is_leaf
properties
array2SortByTree(data, idKey, parentKey, startWith?, level?, arrOut?, parentIndex?)
Purpose: Sort array in hierarchical order (Oracle CONNECT BY style)
Returns: Flat array sorted hierarchically with $level
, $index
, $tree_index
properties
array2SortAndWeight(data, idKey, parentKey, weightKey, startWith?, level?, rootWeight?, arrOut?, parentIndex?)
Purpose: Create weighted tree with percentage calculations
Additional Parameters:
weightKey
: Field name containing weight valuesReturns: Tree with weight calculations: $sum_weight
, $weight_percent
, $parent_weight_percent
, $root_weight_percent
tree2Array(treeData, childrenKey, parentValue?, level?)
Purpose: Convert tree structure back to flat array
Parameters:
treeData
: Tree structure arraychildrenKey
: Children property name (e.g., 'children', 'subs')parentValue
: Starting parent ID valuelevel
: Starting levelReturns: Flat array with auto-generated $id
, $parent_id
fields
Full TypeScript support with generic types and interfaces:
import { Array2Tree, TreeNode } from '@dqcai/tree';
interface Department {
id: number;
parent_id: number | null;
name: string;
budget: number;
}
const converter = new Array2Tree();
const tree: TreeNode<Department>[] = converter.array2Tree(departments, 'id', 'parent_id');
Work with any field names in your database:
// Custom field names
const result = converter.array2Tree(
data,
'custom_id', // Your ID field
'parent_custom_id', // Your parent ID field
null // Root value
);
-- Complex recursive SQL query
WITH RECURSIVE department_tree AS (
SELECT id, parent_id, name, budget, 1 as level
FROM departments
WHERE parent_id IS NULL
UNION ALL
SELECT d.id, d.parent_id, d.name, d.budget, dt.level + 1
FROM departments d
JOIN department_tree dt ON d.parent_id = dt.id
)
SELECT * FROM department_tree ORDER BY level, name;
// Simple flat query
const departments = await db.query('SELECT * FROM departments');
// Client-side tree processing
const tree = converter.array2SortByTree(departments, 'id', 'parent_id');
"Transformed our architecture from complex backend tree processing to simple client-side operations. Performance improved dramatically!" - Senior Frontend Developer
"Perfect for migrating legacy systems to modern frontend-heavy architectures. Saved months of development time." - Tech Lead
"The weighted tree calculations are perfect for our KPI dashboard. No more complex SQL aggregations!" - Data Engineer
import { Array2Tree } from '@dqcai/tree';
import { useState, useEffect } from 'react';
function TreeComponent() {
const [treeData, setTreeData] = useState([]);
useEffect(() => {
fetchFlatData().then(data => {
const converter = new Array2Tree();
const tree = converter.array2Tree(data, 'id', 'parent_id');
setTreeData(tree);
});
}, []);
return <TreeRenderer data={treeData} />;
}
import { Array2Tree } from '@dqcai/tree';
export default {
data() {
return {
treeData: []
}
},
async mounted() {
const flatData = await this.fetchData();
const converter = new Array2Tree();
this.treeData = converter.array2Tree(flatData, 'id', 'parent_id');
}
}
// Also works perfectly on Node.js backend
import { Array2Tree } from '@dqcai/tree';
app.get('/api/tree', async (req, res) => {
const flatData = await database.query('SELECT * FROM categories');
const converter = new Array2Tree();
const tree = converter.array2Tree(flatData, 'id', 'parent_id');
res.json(tree);
});
typescript
javascript
tree-structure
database-arrays
hierarchical-data
frontend-processing
client-side-logic
data-transformation
parent-child-relationships
nested-objects
oracle-connect-by
weighted-trees
business-logic-migration
performance-optimization
modern-architecture
MIT License - see LICENSE file for details.
npm install @dqcai/tree
Transform your data architecture and move processing from server to client with the most powerful tree conversion library for JavaScript and TypeScript!
@dqcai/tree - Bridge the gap between database and frontend with powerful tree transformations! 🌳⚡
FAQs
A TypeScript library for converting arrays to tree structures and vice versa
We found that @dqcai/tree demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
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.
Security News
Socket CEO Feross Aboukhadijeh discusses the recent npm supply chain attacks on PodRocket, covering novel attack vectors and how developers can protect themselves.
Security News
Maintainers back GitHub’s npm security overhaul but raise concerns about CI/CD workflows, enterprise support, and token management.
Product
Socket Firewall is a free tool that blocks malicious packages at install time, giving developers proactive protection against rising supply chain attacks.