I'm hoping you guys can help me figure out how to separate the values at the root level. The expected output is shown below but what I'm getting is all the values get placed under the "ABC" item when there should be two objects at the root level in this example.
Note: there can be 1 or many different root level values that can have n levels separated by '|' character.
Input
"values": [
"ABC|A Type 1",
"ABC|A Type 2|B Type 1",
"ABC|A Type 2|B Type 2",
"XYZ|X Type 1",
"XYZ|X Type 2",
"XYZ|X Type 3|Y Type 1",
]
Expected Output
[
{
"value": "ABC",
"label": "ABC",
"children": [
{
"value": "A Type 1",
"label": "A Type 1",
},
{
"value": "A Type 2",
"label": "A Type 2",
"children": [
{
"value": "B Type 1",
"label": "B Type 1",
},
{
"value": "B Type 2",
"label": "B Type 2",
}
]
}
]
},
{
"value": "XYZ",
"label": "XYZ",
"children": [
{
"value": "X Type 1",
"label": "X Type 1",
},
{
"value": "X Type 2",
"label": "X Type 2",
},
{
"value": "X Type 3",
"label": "X Type 3",
"children": [
{
"value": "Y Type 1",
"label": "Y Type 1",
}
]
}
]
}
]
What I have tried so far:
const input = {
"values": [
"ABC|A Type 1",
"ABC|A Type 2|B Type 1",
"ABC|A Type 2|B Type 2",
"XYZ|X Type 1",
"XYZ|X Type 2",
"XYZ|X Type 3|Y Type 1",
]
};
let tree = {};
function fillTree(steps) {
let current = null,
existing = null,
i = 0;
for (let y = 0; y < steps.length; y++) {
if (y === 0) {
if (!tree.children || typeof tree.children == 'undefined') {
tree = { label: steps[y], value: steps[y], children: [] };
}
current = tree.children;
} else {
existing = null;
for (i = 0; i < current.length; i++) {
if (current[i].label === steps[y]) {
existing = current[i];
break;
}
}
if (existing) {
current = existing.children;
} else {
if (y === steps.length - 1) {
current.push({ label: steps[y], value: steps[y] });
} else {
current.push({ label: steps[y], value: steps[y], children: [] });
}
current = current[current.length - 1].children;
}
}
}
}
for (let x = 0; x < input.values.length; x++) {
let steps = input.values[x].split('|');
fillTree(steps);
}
console.log('tree', JSON.stringify(tree));