I have an array formatted like so:
[
{
"Level": "0",
"Text": "My text 1",
},
{
"Level": "1",
"Text": "My text 2",
},
{
"Level": "1",
"Text": "My text 3",
},
{
"Level": "2",
"Text": "My text 4",
},
{
"Level": "3",
"Text": "My text 5",
},
{
"Level": "1",
"Text": "My text 6",
},
{
"Level": "0",
"Text": "My text 7",
}
]
I want to convert it to be formatted like so:
[
{
"Text": "My text 1",
"nodes": [
{
"Text": "My text 2",
},
{
"Text": "My text 3",
"nodes": [
{
"Text": "My text 4",
"nodes": [
{
"Text": "My text 5",
}
]
}
]
},
{
"Text": "My text 6",
}
]
},
{
"Text": "My text 7",
}
]
It is fine if the "Level" key is not removed from each object. There could be 10s of thousands of objects in the array, so speed is important. I can't figure out a way to efficiently do this because the parent node needs to be tracked to know where to place the children. The "Level" key is guaranteed to be greater than or equal to 0. The "Level" key is also guaranteed to be a maximum of 1 higher than the "Level" key of the previous element in the array. In other words, 0 <= array[i].Level <= array[i+1].Level - 1
. Thanks.