Q:

Write a JavaScript program to nest a given flat array of objects linked to one another recursively

0

Write a JavaScript program to nest a given flat array of objects linked to one another recursively.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

const nest = (items, id = null, link = 'parent_id') =>
  items
    .filter(item => item[link] === id)
    .map(item => ({ ...item, children: nest(items, item.id) }));
// One top level comment
const comments = [
  { id: 1, parent_id: null },
  { id: 2, parent_id: 1 },
  { id: 3, parent_id: 1 },
  { id: 4, parent_id: 2 },
  { id: 5, parent_id: 4 }
];
const nestedComments = nest(comments); 
console.log(nestedComments);

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now