Answer the question
In order to leave comments, you need to log in
How to turn a flat array into a tree?
I need to determine in which elements and in what number there are child subelements - in other words, compose a treeview from a json file so that I can then turn these elements into this .
I tried to solve everything through recursion, but now I'm in a stupor. The function simply returns undefined.
Here is the recursion
function f1(p) {
for (i = 0; i < p.length; i++) {
var z = data.filter(obj => obj.parentId === p[i].id);
if(z){
f1(z);
}
else continue;
}
}
$(document).ready(function() {
var tree = document.getElementsByClassName("tree");
$.getJSON('some_json_ssilka', function(data) {
function f1(p) {
for (i = 0; i < p.length; i++) {
var z = data.filter(obj => obj.parentId === p[i].id);
if(z){
f1(z);
}
else continue;
}
}
var level = data.filter(obj => obj.parentId === -1);
console.log(f1(level));
});
});
[
{
"id":2,
"title":"Folder 1",
"parentId":-1
},
{
"id":3,
"title":"Test",
"parentId":1
},
{
"id":-1,
"title":"Folder 2",
"parentId":null
},
{
"id":1,
"title":"Folder 2",
"parentId":-1
},
{
"id":4,
"title":"Wrike",
"parentId":2
},
{
"id":5,
"title":"Tester",
"parentId":1
}
]
Answer the question
In order to leave comments, you need to log in
tried to solve everything through recursion
const createTree = (data, idProp, parentProp, parentId) =>
data.reduce((acc, n) => (parentId === n[parentProp] && acc.push({
...n,
children: createTree(data, idProp, parentProp, n[idProp]),
}), acc), []);
const tree = createTree(data, 'id', 'parentId', null);
const createTree = (data, idProp, parentProp) => {
const tree = Object.fromEntries(data.map(n => [ n[idProp], { ...n, children: [] } ]));
return Object
.values(tree)
.filter(n => !(tree[n[parentProp]] && tree[n[parentProp]].children.push(n)));
};
const tree = createTree(data, 'id', 'parentId');
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question