var key = 1; // keys start at 1 let addPaths = (root, paths) => { if (!paths || paths.length == 0) return; let path = paths.shift(); //add nodes for the current path addNodes(root, path.split('//')); // keep going until all paths have been processed addPaths(root, paths); }; let addNodes = (root, nodeList) => { if (!nodeList || nodeList.length == 0) return; let title = nodeList.shift(); // find node under root with matching title let isRootNode = Array.isArray(root); node = (isRootNode ? root : root.children || []).find((node) => { return node.title == title; }); if (!node){ node = { title: title, key: key++ } // are we at root of object? if (isRootNode) root.push(node); else { if (!root.children) root.children = []; root.children.push(node); root.folder = true; } } addNodes(node, nodeList); }; let parse = (string) => { let object = []; let nodes = string.split(','); addPaths(object, nodes); return object };
console.log(JSON.stringify(parse("A//a1,A//a2,A//a3//a31,A//a3//a32,B,C//c1,C//c2"), null, 2));
Result:
[ { "title": "A", "key": 1, "children": [ { "title": "a1", "key": 2 }, { "title": "a2", "key": 3 }, { "title": "a3", "key": 4, "children": [ { "title": "a31", "key": 5 }, { "title": "a32", "key": 6 } ], "folder": true } ], "folder": true }, { "title": "B", "key": 7 }, { "title": "C", "key": 8, "children": [ { "title": "c1", "key": 9 }, { "title": "c2", "key": 10 } ], "folder": true } ]