I have the following piece of json, it follows a specific pattern but each object can have any number of children and each of those children objects can have any number of children ..
[
{
"name": "1st level",
"parentId": "",
"id": "dummyvalue1",
"children": [
{
"name": "2nd level child",
"parentId": "dummyvalue1",
"id": "dummyvalue2"
},
{
"name": "another 2nd level child",
"id": "dummyvalue3",
"children": [
{
"name": "3rd level child",
"id": "dummyvalue4",
"children": [
{
"name": "4th level child",
"parentId": "dummyvalue4",
"id": "dummyvalue5"
}
],
"parentId": "dummyvalue3"
}
],
"parentId": "dummyvalue1"
}
]
}
]
The problem is, I only need to access objects at a specific depth within this nested object/array structure.
And that depth is dynamic.
If the depth equals 3, then I would like to add a new dummy object into the children array for that level. So the new structure would look like this ..
[
{
"name": "1st level",
"parentId": "",
"id": "dummyvalue1",
"children": [
{
"name": "2nd level child",
"parentId": "dummyvalue1",
"id": "dummyvalue2"
},
{
"name": "another 2nd level child",
"id": "dummyvalue3",
"children": [
{
"name": "3rd level child",
"id": "dummyvalue4",
"children": [
{
"name": "4th level child",
"parentId": "dummyvalue4",
"id": "dummyvalue5"
}
],
"parentId": "dummyvalue3"
},
{
"name": "NEW OBJECT",
"parentId": "dummyvalue3",
"id": "random"
}
],
"parentId": "dummyvalue1"
}
]
}
]
Is there a clean way to do this? Instead of huge loops trying to iterate to the right level. Also dont think I can use dot notation since the number of levels and the depth variable is dynamic
"name": "2nd level child"there is a children property, and that path also contain 3rd level depth? you want to push the new object in both the path at level 3?childrento insert usingdummyvalue4as an identifier for the parent