M
M
Michael2019-10-19 23:38:24
JavaScript
Michael, 2019-10-19 23:38:24

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;
   }
}

Code outline
$(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));
  });
});

Initial data:
[
    {
       "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

1 answer(s)
0
0xD34F, 2019-10-19
@Misha5

tried to solve everything through recursion

Of course you can recurse:
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);

But not necessarily:
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 question

Ask a Question

731 491 924 answers to any question