A
A
ajky2016-12-05 20:46:08
JavaScript
ajky, 2016-12-05 20:46:08

How is it optimized to convert a flat structure to a tree structure in JS?

An array with objects is transmitted from the server, it looks something like this:

[
  {
    id: 1,
    path: [2,3]
  },
  {
    id: 2,
    path: []
  },
  {
    id: 3,
    path: [2]
  }
]

path - path by id
, starting from the root of the tree
[
  {
    id: 2,
    children: [{
      id: 3,
      children: [
        {id: 1},
        {id: 4}
      ]
    }]
  }
]

Nothing comes to mind, except to run through the array, find out the maximum number of levels and run a loop in which a new array will be built starting from the root documents, going through each level ... but it seems to me that there are much better ways :/
PS if possible - code, please. Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Korotaev, 2016-12-05
@ajky

codepen.io/anon/pen/mOxBeQ?editors=1012
Made based on the mutability of objects in JS, for each item I read only the last element from the path
in IE will not work because Object.assign, if critical, you can replace it with what -something similar
PS: children is not declined, it's already plural)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question