implement tree structure with parent id javascript

Solutions on MaxInterview for implement tree structure with parent id javascript by the best coders in the world

showing results for - "implement tree structure with parent id javascript"
Emmanuel
27 Aug 2020
1const data = [
2  { id: 56, parentId: 62 },
3  { id: 81, parentId: 80 },
4  { id: 74, parentId: null },
5  { id: 76, parentId: 80 },
6  { id: 63, parentId: 62 },
7  { id: 86, parentId: 74 },
8];
9const idMapping = data.reduce((acc, el, i) => {
10  acc[el.id] = i;
11  return acc;
12}, {});
13
14let root = [];
15data.forEach(el => {
16  // Handle the root element
17  if (el.parentId === null || !idMapping[el.parentId]) {
18	root.push(el);
19  } else {
20    // Use our mapping to locate the parent element in our data array
21    const parentEl = data[idMapping[el.parentId]];
22    // Add our current el to its parent's `children` array
23    parentEl.children = [...(parentEl.children || []), el];
24  }
25});
26
27console.log(root);
28