Converting flat array of object to array of nested objects

Viewed 396

I'm trying to convert a flat array of objects coming from my database, to feed to react-table which needs a nested structure to be able to manage expandable sub rows.

I've made a CodeSandbox which is pretty self-explanatory :

https://codesandbox.io/s/tender-chatterjee-kdssi?file=/src/App.js

Basically, my original data is structured like so:

  [
    {
      code: "A0",
      parent: ""
    },
    {
      code: "A01",
      parent: "A0"
    },
    {
      code: "A011",
      parent: "A01"
    },
    {
      code: "B0",
      parent: ""
    },
    {
      code: "B01",
      parent: "B0"
    },
    {
      code: "B011",
      parent: "B01"
    }
  ]

And I want to convert it to this structure :

  [
    {
      code: "A0",
      parent: "",
      subRows: [
        {
          code: "A01",
          parent: "A0",
          subRows: [
            {
              code: "A011",
              parent: "A01"
            }
          ]
        }
      ]
    },
    {
      code: "B0",
      parent: "",
      subRows: [
        {
          code: "B01",
          parent: "B0",
          subRows: [
            {
              code: "B011",
              parent: "B01"
            }
          ]
        }
      ]
    }
  ]

I've tried some recursive ways of doing it, but they're leaving behind some options, so I'd gladly accept some help on this.

Thank you.

2 Answers

This can be done with a fairly simple recursive method.

const mockData = [{
    code: "A0",
    parent: ""
  },
  {
    code: "A01",
    parent: "A0"
  },
  {
    code: "A011",
    parent: "A01"
  },
  {
    code: "B0",
    parent: ""
  },
  {
    code: "B01",
    parent: "B0"
  },
  {
    code: "B011",
    parent: "B01"
  }
];


const hierarchize = (parent, list) => {
  const children = list.filter(x => x.parent == parent.code);
  children.forEach(child => hierarchize(child, list));
  parent.subRows = children;
}

const topLevel = mockData.filter(x => x.parent == "");
topLevel.forEach(top => hierarchize(top, mockData));

console.log(topLevel);

Related