1 回答
TA贡献1796条经验 获得超7个赞
始终优先考虑可读性而不是花哨:
const arr = [{
"fileName": "operations.pptx",
"fileSize": 23642178,
"fileType": "pptx",
"fsLocation": "Events/Plays/Technologies/operations.pptx",
"createDate": "2019-01-08T08:00:00Z",
"editDate": "2019-01-09T08:00:00Z",
"version": "15.0"
},
{
"createDate": "2019-10-03T07:00:00Z",
"fileType": "pptx",
"fsLocation": "Events/Plays/Technologies/Continuity/technology.pptx",
"fileSize": 46845322,
"fileName": "technology.pptx",
"editDate": "2019-10-03T07:00:00Z",
"version": "10.0"
},
{
"fileName": "Solution.pdf",
"createDate": "2016-06-16T22:42:16Z",
"fileSize": 275138,
"fsLocation": "Events/Plays/Technologies/Solution.pdf",
"fileType": "pdf",
"editDate": "2016-06-16T22:42:16Z",
"version": "1.0"
}
]
const tree = {
name: 'root',
path: '',
children: []
}
for (const e of arr) {
let node = tree
const nodenames = e.fsLocation.split('/')
while (nodenames.length > 0) {
const nodename = nodenames.shift()
if (!node.children.map(e => e.name).includes(nodename)) {
node.children.push({
name: nodename,
path: [node.path, nodename].join('/'),
children: []
})
}
node = node.children.filter(e => e.name === nodename)[0]
}
}
console.log(JSON.stringify(tree, null, 2));
返回树:
{
"name": "root",
"path": "",
"children": [
{
"name": "Events",
"path": "/Events",
"children": [
{
"name": "Plays",
"path": "/Events/Plays",
"children": [
{
"name": "Technologies",
"path": "/Events/Plays/Technologies",
"children": [
{
"name": "operations.pptx",
"path": "/Events/Plays/Technologies/operations.pptx",
"children": []
},
{
"name": "Continuity",
"path": "/Events/Plays/Technologies/Continuity",
"children": [
{
"name": "technology.pptx",
"path": "/Events/Plays/Technologies/Continuity/technology.pptx",
"children": []
}
]
},
{
"name": "Solution.pdf",
"path": "/Events/Plays/Technologies/Solution.pdf",
"children": []
}
]
}
]
}
]
}
]
}
添加回答
举报