How do I build a JSON object thats is compatible with react-sortable-tree (every nested object has title, children) to render the file tree.
For example, I have this array of filepaths.
var filePaths = [
"Diagnoses/Endocrine disorders/Thyroid disorders/Congenital hypothyroidism",
"Diagnoses/Endocrine disorders/Thyroid disorders/Acquired hypothyroidism",
"Diagnoses/Endocrine disorders/Thyroid disorders/Acquired hypothyroidism/Postsurgical hypothyroidism"
];
I would like a JSON Object like this.
var treeData = [
{
title: 'Diagnoses',
children: [{
title: 'Endocrine disorders',
children: [{
title: 'Thyroid disorders',
children: [
{
title: 'Congential hypothyroidism'
},
{
title: 'Acquired hypothyroidism',
children: [{
title: 'Postsurgical hypothyroidism'
}]
}
]
}]
}]
}
];
Edit: I tried this but after the first iteration, I'm overwriting the children property of the whole tree. I tried a couple of checks to stop that but they didn't quite pan out.
var hierarchy = filePaths.reduce(function(hier,path){
var x = hier;
path.split('/').forEach(function(item, index, array){
if(x[0].title != item){
x[0].title = item;
}
// console.log(index, array.length)
if (index != array.length - 1 && !x[0].children){
x[0].children = [{
title: ''
}];
}
x = x[0].children;
});
return hier;
}, [{title: ''}]);