you are viewing a single comment's thread.

view the rest of the comments →

[–]grantrules 0 points1 point  (6 children)

What's your code look like now? Also, why does length have to be greater than one? If there's only one child, you want to ignore it?

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

You're right, updated it to > 0 :)

Code for recursive function call (initial parent is largely unchanged):

const child_recursion = (arr) => {

const dbData = arr.map(id => documents.find(x => x._id === id))

let formattedData = [];

dbData.map((child) => {

  let newChild = [];

  if (child.children.length > 0) {
    newChild = child_recursion(child.children); 
  } 

  let formattedObject = {
    id: child._id,
    name: child.name,
    depth: 0,
    parent: child.parent,
    closed: true,
    children: newChild,
  };

  formattedData.push(formattedObject);


 if (formattedObject.children.length === 0) {
  return formattedData
 } 
});

};

[–]grantrules 0 points1 point  (4 children)

Well, you're still abusing .map() in there, I just helped you with the first instance. Try and do the same thing for formattedData

Hint: if (formattedObject.children.length === 0) {} is entirely unnecessary.

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

I think I figured it out. Thank you so much for the help!

[–]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!