[
id:1,name:"Text",parent:0,
id:2,name: "Folder in Parent Folder with id 1", parent: 1,
id:555, name: "Rekursive folder in Folder 2....", parent:2
]
[
id:1, name:"Text",
children: [
id:2,name: "Folder in Parent Folder with id 1",
children: [
id:555, name: "Rekursive folder in Folder 2...."
]
]
var rawData = [
{ id:1,name:"Root element",parent:0 },
{ id:2,name: "Child of the first element", parent: 1},
{ id:555, name: "Child of the second element", parent:2}
];
function pack( data ){
const childs = id =>
data.filter( item => item.parent === id )
.map(
({id,name}) => ({id,name, children: childs(id)})
).map(
({id,name,children}) => children.length ? {id,name, children} : { id, name }
);
return childs(0);
}
console.log(JSON.stringify(pack(rawData)))
function test4( list ) {
var map = {}, node, roots = [], i;
for (i = 0; i < list.length; i += 1) {
map[list[i].id] = i;
list[i].children = [];
}
for (i = 0; i < list.length; i += 1) {
node = list[i];
if (node.parent) {
list[map[node.parent]].children.push(node);
} else {
roots.push(node);
}
}
return roots;
}