I have data coming in that is in a linear format, e.g.:
const data = [
  {
    "id": "1",
    "parentId": null
  },
  {
    "id": "1.1",
    "parentId": "1"
  },
  {
    "id": "1.2",
    "parentId": "1"
  },
  {
    "id": "2",
    "parentId": null
  },
  {
    "id": "2.1",
    "parentId": "2"
  },
  {
    "id": "3",
    "parentId": null
  },
  {
    "id": "3.1",
    "parentId": "3"
  },
  {
    "id": "3.1.1",
    "parentId": "3.1"
  },
  {
    "id": "3.1.1.1",
    "parentId": "3.1.1"
  }
];
What I'm wanting to do is convert it to be in a hierarchical format, e.g.:
const hierarchicalData = [
  {
    "id": "1",
    "children": [
      {
        "id": "1.1",
      },
      {
        "id": "1.2",
      }
    ]
  },
  ...
]
I understand that there will need to be a level on recursion that can go on, but I get stuck at getting past the first level without having to brute force this thing knowing the number of levels beforehand.
I've been at this for roughly 3 hours now and can't quite grasp my head around how to do it.
This is an example demonstrating my issue:
var output = [];
$.each(data, function(index, value) {
    if (value.parentId === null) {
    value.children = [];
    output.push(value);
  } else {
    $.each(output, function(innerIndex, innerValue) {
        if (value.parentId === innerValue.id) {
        innerValue.children.push(value);
        return;
      }
    });
  }
});
console.log(output);