I need your help for create a tree like data structure with given JSON as shown below and required output structure already given below. I am a beginner in programming and I have only a little knowledge in data structure
[
"",
[
"Test",
[
"Test/sample",
[
"Test/sample/sample1"
]
],
[
"Test/test3"
]
],
[
"Test1",
[
"Test1/test2"
]
],
[
"cat"
]
]
{
"key": "Image",
"label": "Image",
"icon": 'pi pi-folder',
"children": []
},
{
"key": "Test",
"label": "Test",
"icon": "pi pi-folder",
"children": [
{
"key": "Test/sample",
"label": "Sample",
"icon": "pi pi-folder",
"children": [{
"key": "Test/sample/sample1",
"label": "Sample1",
"icon": 'pi pi-folder',
"children": []
}]
},
{
"key": "Test/test3",
"label": "test3",
"icon": "pi pi-folder",
"children": []
},
]
},
{
"key": "Test1",
"label": "Test1",
"icon": "pi pi-folder",
"children": [{
"key": "Test1/test2",
"label": "test2",
"icon": "pi pi-folder",
"children": []
}]
},
{
"key": "cat",
"label": "cat",
"icon": "pi pi-folder",
"children": []
},
]
Above structure is image file directory and directory name is indicated by label and icon is indicating directory, children show sub directory
It can easily archive with recursive function
const icon = "pi pi-folder"; var a = [ "", [ "Test", [ "Test/sample", [ "Test/sample/sample1" ] ], [ "Test/test3" ] ], [ "Test1", [ "Test1/test2" ] ], [ "cat" ] ] /** * @param {Array} arr The child array */ function createChildNode(arr) { let key = "Image"; let label = "Image"; let children = []; if (arr.length >= 1) { key = arr[0]; label = key.includes("/")? key.split("/").pop(): key; label = label.charAt(0).toUpperCase() + label.slice(1); for (let index = 1; index < arr.length; index++) { const element = arr[index]; children.push(createChildNode(element)); } } return {key: key, label: label, icon: icon, children: children}; } var b = [] for (let index = 0; index < a.length; index++) { const element = a[index]; b.push(createChildNode(element)); } console.log(b);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.