Would something like this work? Not sure if it's more performant, but maybe a little?
javascript
const as_obj = data.reduce((accum, curr) => {
const { category_name, isparent, parent } = curr;
if (isparent && accum[category_name]) {
// This is a parent, but we've already seen one of its children;
// we created the parent key for that already.
return accum;
}
if (isparent && !accum[category_name]) {
// This is the first time we've seen the parent key, creating an object for it.
return { ...accum, [category_name]: { ...curr, children: [] } };
}
if (parent && !accum[parent]) {
// We haven't seen this child's parent yet, but we'll make a place for it.
accum[parent] = { category_name, children: [] };
}
const children = [ ...accum[parent].children, curr];
return { ...accum, [parent]: { ...accum.parent, children } };
}, {});
const res = Object.values(as_obj);