How to make a tree-like array structure in javascript from an array of three fields id, name, parent?
-
Tell me if I have an array of a similar type and is stored on the server in a similar structure.
[ 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 ]
I would like to draw this data in the list, draw the received data from an array, where parent is the parent element.
[ id:1, name:"Text", children: [ id:2,name: "Folder in Parent Folder with id 1", children: [ id:555, name: "Rekursive folder in Folder 2...." ] ]
How do I convert this recursively since the nesting level is unknown?JavaScript Anonymous, Mar 30, 2020 -
whip up something like this
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)))Anonymous -
Just a couple of lines of code, which, if desired, can be combined into one to the detriment of clarity.
const map = Object.assign({} , ...arr.map(v =>
({ [v.id]: Object.assign(v, { children: [] }) })
))
const tree = Object.values(map).filter(v =>
!(v.parent && map[v.parent].children.push(v))
)Finn Downs -
var arr = [
{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}
];
function makeTree(array, parent) {
var tree = {};
parent = typeof parent !== 'undefined' ? parent : {id: 0};
var childrenArr = array.filter(function(child) {
return child.parent == parent.id;
});
if (childrenArr.length > 0) {
var childrenObj = {};
childrenArr.forEach(function(child) {
childrenObj[child.id] = child;
});
if (parent.id == 0) {
tree = childrenObj;
} else {
parent.children = childrenObj;
}
childrenArr.forEach(function(child) {
makeTree(array, child);
})
}
return tree;
};
console.log(makeTree(arr));Anonymous -
As I understand it, the input data is an array of objects with any id?
Then you can do this:
You create an empty array constant, step through the input data and shove the children where necessary.
All.Anonymous
4 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!