简体   繁体   中英

How to convert array of string to nested JSON object?

I want to display all the files and folders present in the blob storage in my front end. for which I am using PrimeNG tree component. however, I am not able to convert my response to the format required by primeNG.

here is the actual response:

"filenames": [
"/30",
"/mtcagent.log",
"/spe9_xf.rst/bin/sbin/spe9_rgg-prop_ycoer.fbin",
"/spe9_xf.rst/bin/sbin/spe.fbin"
]

expected:

[
{"label": "30",
"Icon": "pi pi-folder"
},
{
"label": "mtcagent.log",
"Icon": "pi pi-folder"
},
{
"label": "spe9_xf.rst",
"Icon": "pi pi-folder",
"children": [
{
"label": "bin",
"Icon": "pi pi-folder",
"children": [
{
"label": "sbin",
"Icon": "pi pi-folder",
"children": [
{
"label": "spe9_rgg-prop_ycoer.fbin",
"Icon": "pi pi-file",
},
{
"label": "spe.fbin",
"Icon": "pi pi-file",
}
]
}
]
}
]
}
]

This is my code so far:

 var arr = [ "abc.rft", "ccc.rft", "spe9_sgrid_long_rstcreation.rst/bin/sbin/spe9_batch-grid.dat.binfiles" ]; var arrOfObjs = new Array(); for (let i = 0; i < arr.length; i++) { var obj = { "expandedIcon": "pi pi-folder-open", "collapsedIcon": "pi pi-folder" }; obj.label = arr[i]; arrOfObjs.push(obj); } arrOfObjs.forEach(e => { if (e.label.indexOf('/') == -1) { } else { var carray = new Array(); var x = e.label.split('/'); e.label = x[0]; obj.label = e.label; carray.push(obj); console.log('carray', carray) e['children'] = JSON.stringify(carray); console.log('sss', arrOfObjs) } });

您可以使用 .map 高阶函数来执行此操作。

Or maybe use :

JSON.parse(JSON.stringify(carray));

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM