Tree & Hierarchy Utilities
Data Transformation
When fetching Taxonomies or Menus from the API, the data is often flat (containing parent_id references). These utilities help transform that data.
buildTree()
Transforms a flat array of objects into a nested hierarchical tree structure based on parent-child relationships.
Signature:
function buildTree(data, idKey = "term_id")
flattenTree()
Recursively flattens a nested tree structure back into a simple list array.
Signature:
function flattenTree(nodes)
DOM Rendering
Once you have a nested tree array, you can render it into HTML effortlessly.
renderTreeAsSelectOptions()
Recursively populates an HTML <select> element with <option> tags, visually indenting child items with dashes (e.g., — — Sub-category).
Signature:
function renderTreeAsSelectOptions(tree, selectEl, idKey = "term_id", nameKey = "name", depth = 0)
renderTreeAsCheckbox()
Generates nested HTML checkboxes for hierarchical data selection, properly maintaining visual margins for child levels.
Signature:
function renderTreeAsCheckbox(tree, idKey = "term_id", nameKey = "name", inputName = "categories[]", depth = 0)
loadTaxonomy()
A high-level utility that fetches a specific taxonomy from the API and instantly populates a target <select> element.
Signature:
async function loadTaxonomy(resource, options = {})
// Options: { targetSelector, langId, selectedId, nameKey, idKey, queryParams }