JSFiddle - React, Tailwind, and code Playground

by Bobkorinek

JavaScript

const input = [{
    "_id": "123",
    "name": "ABC",
    "parentID": ""
  },
  {
    "_id": "645",
    "name": "ABC 2",
    "parentID": "123"
  },
  {
    "_id": "65",
    "name": "ABC 3",
    "parentID": "645"
  }
]

function map(data) {
 	const childMap = data.reduce((map, child) => {
  	return {...map, [child._id]: {...child}};
  }, {});
  
  const root = [];
  
  Object.values(childMap).forEach((child) => {
  	if (child.parentID) {
    	if (childMap[child.parentID]){
        const parent = childMap[child.parentID];
        if (!parent.children) {
          parent.children = [];
        } 

        parent.children.push(child)
      }
    } else {
    root.push(child)
    }
  })
  
  return chi
}