I have the following array of objects. I would like to sort the array so that all child options are placed next to its parent. Most of the solutions are on tree structure where I need it in a flat structure.
Also I need a level key which indicates the level of the option.
[
 {
    "id": 1,
    "name": "Parent"
 },
 {
    "id": 2,
    "name": "Child 1",
    "parent_id": 1
 },
 {
    "id": 3,
    "name": "Grand Child 1",
    "parent_id": 2
 },
 {
    "id": 4,
    "name": "Grand Child 2",
    "parent_id": 2
 },
 {
    "id": 5,
    "name": "Child 2",
    "parent_id": 1
 },
 {
    "id": 7,
    "name": "Grand Child 3",
    "parent_id": 2
 },
]
I want all child to be places next to it's parent like this
[
 {
    "id": 1,
    "name": "Parent",
    "level": 1
 },
 {
    "id": 2,
    "name": "Child 1",
    "parent_id": 1,
    "level": 2
 },
 {
    "id": 3,
    "name": "Grand Child 1",
    "parent_id": 2,
    "level": 3
 },
 {
    "id": 4,
    "name": "Grand Child 2",
    "parent_id": 2,
    "level": 3
 },
 {
    "id": 7,
    "name": "Grand Child 3",
    "parent_id": 2,
    "level": 3
 },
 {
    "id": 5,
    "name": "Child 2",
    "parent_id": 1,
    "level": 2
 },
]
I've seen a solution but it works only 1 level
 
    