79814456

Date: 2025-11-08 21:24:40
Score: 2
Natty:
Report link

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);
Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Ends in question mark (2):
  • Low reputation (1):
Posted by: Rodrigo Reis