如何構建與react-sortable-tree兼容的JSON對象(每個嵌套對象都有title,children)來呈現文件樹。例如,我有這個文件路徑的數組。文件路徑字符串到文件樹JSON的數組(與react-sortable-tree兼容)
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"
];
我想要一個像這樣的JSON對象。
var treeData = [
{
title: 'Diagnoses',
children: [{
title: 'Endocrine disorders',
children: [{
title: 'Thyroid disorders',
children: [
{
title: 'Congential hypothyroidism'
},
{
title: 'Acquired hypothyroidism',
children: [{
title: 'Postsurgical hypothyroidism'
}]
}
]
}]
}]
}
];
編輯:我試過這個,但在第一次迭代後,我覆蓋了整棵樹的子屬性。我嘗試了一些檢查來阻止它,但他們沒有完全平息。
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: ''}]);
你至今寫什麼碼?你卡在哪裏? – smarx
@smarx我剛剛編輯帖子,我卡住了。謝謝。 – schintha