JSFiddle - React, Tailwind, and code Playground
by manoj jasti
JavaScript
/**
* Converts a multilevel facet JSON to a parent-child structure using level as an indicator.
* @param {Object} multilevel - The multilevel facet JSON.
* @returns {Object} - The parent-child structured JSON.
*/
function convertToParentChild(multilevel) {
const result = {};
const levels = {};
// Process each item in the list
multilevel.list.forEach(item => {
const level = item.level;
const filterField = item.filterField;
// Initialize the level if not already done
if (!levels[level]) {
levels[level] = [];
}
// Add the item to the appropriate level
levels[level].push(item);
// Process the breadcrumb if it exists
if (item.breadcrumb) {
const breadcrumbLevel = item.breadcrumb.level;
if (!levels[breadcrumbLevel]) {
levels[breadcrumbLevel] = [];
}
levels[breadcrumbLevel].push(item.breadcrumb);
}
});
// Build the parent-child structure
Object.keys(levels).sort((a, b) => a - b).forEach(level => {
levels[level].forEach(item => {
if (item.level === 1) {
result[item.filterField] = item;
} else {
const parentLevel = item.level - 1;
const parent = levels[parentLevel].find(parentItem => parentItem.filterField === item.filterField);
if (parent) {
if (!parent.children) {
parent.children = [];
}
parent.children.push(item);
}
}
});
});
return result;
}
// Example usage
const multilevel = {
list: [
{
breadcrumb: {
level: 1,
filterField: "categoryPath",
values: [{ name: "Electronics" }]
},
filterField: "categoryPath",
level: 2,
values: [{ name: "TV and...