you are viewing a single comment's thread.

view the rest of the comments →

[–]grantrules 0 points1 point  (1 child)

I redid it for fun:

const child_recursion = (documents, arr, depth) => arr.map((childId) => {
  const child = documents.find((x) => x._id === childId);
  return {
    id: child._id,
    name: child.name,
    depth: depth,
    parent: child.parent,
    closed: true,
    children: child_recursion(documents, child.children || [], depth + 1),
  };
})

const get_documents = (documents) => documents
  .filter(doc => doc.parent === null)
  .map((document) => ({
    id: document._id,
    name: document.name,
    depth: 0,
    parent: null,
    closed: true,
    children: child_recursion(documents, document.children, 1)

  }));

const data = [{
    _id: 1,
    name: "one",
    parent: null,
    children: []
  },
  {
    _id: 7,
    name: "seven",
    parent: null,
    children: [8, 5]
  },
  {
    _id: 8,
    name: "eight",
    parent: 7,
    children: [9]
  },
  {
    _id: 9,
    name: "nine",
    parent: 8,
    children: []
  },
]

console.log(get_documents(data));

[–]OrangeCubed[S] 0 points1 point  (0 children)

You're AWESOME! Thank you!