As per my original question geared specifically for React (React recursive tree pass JSON path), I have realised the problem is pretty generic.
I have a recursive function that essentially loops through a treelike JSON structure, each time it outputs a branch I want to pass an object of the structures location in the tree like below.. Is there a simpler way to pass the structure? Is the data structure poor / should each chid have a unique ID attached?
My JSON object is below so you can see what I'm working with.
Any help much appreciated!
Level 1 child
{value: "Fruit"}
Level 2 child
{value: "Fruit", nested_values: [{ value: 'Tropical'}] }
Level 3 child
{value: "Fruit", nested_values: [{ value: 'Tropical', nested_values:[{ value: 'Pineapple' }]}] }
Code - kind of works, but then I get all values within the same nested_values array
const createSelectionHierarchy = (data, isSub, level = 2, hierarchy = {}) => {
let children = [];
if (isSub) { level++; }
let obj = {};
obj.name = cat;
const cat = hierarchy.value;
for (let i in data) {
const subcat = data[i].value;
if (typeof(data[i].nested_values) === 'object') { // Sub array found, build structure
obj.values = subcat;
obj.nested_values = [];
hierarchy.nested_values.push(obj);
children.push(
<FilterItem key={i} data={data[i]} hierarchy={hierarchy} level={level}>
{createSelectionHierarchy(data[i].nested_values, true, level, hierarchy)}
</FilterItem>
);
} else { // No sub array, bottom of current branch
children.push(
<p className="filter-item level-last" key={i}>
{data[i].value}
</p>);
}
}
return children;
}
JSON
{
"value": "Fruit",
"occurrence_count": 5,
"nested_values": [{
"value": "Berries",
"occurrence_count": 3,
"nested_values": [{
"value": "Strawberry",
"occurrence_count": 1
}, {
"value": "Blackberry",
"occurrence_count": 1
}, {
"value": "Raspberry",
"occurrence_count": 1
}, {
"value": "Redcurrant",
"occurrence_count": 1
}, {
"value": "Blackcurrant",
"occurrence_count": 1
}, {
"value": "Gooseberry",
"occurrence_count": 1
}, {
"value": "Cranberry",
"occurrence_count": 1
}, {
"value": "Whitecurrant",
"occurrence_count": 1
}, {
"value": "Loganberry",
"occurrence_count": 1
}, {
"value": "Strawberry",
"occurrence_count": 1
}]
}, {
"value": "Tropical",
"occurrence_count": 2,
"nested_values": [{
"value": "Pineapple",
"occurrence_count": 1
}, {
"value": "Mango",
"occurrence_count": 1
}, {
"value": "Guava",
"occurrence_count": 1
}, {
"value": "Passion Fruit",
"occurrence_count": 1
}, {
"value": "Dragon Fruit",
"occurrence_count": 1
}]
}]
}
Desired output
<FilterItem ...... hierarchy={{value: "Fruit"}}>
<FilterItem ...... hierarchy={{value: "Fruit", nested_values: [{ value: 'Tropical'}] }}>
<FilterItem ...... hierarchy={{value: "Fruit", nested_values: [{ value: 'Tropical', nested_values:[{ value: 'Pineapple' }]}] }}>
</FilterItem>
</FilterItem>
</FilterItem>