I have a data structure like this:
[
{name: "Bob"},
{name: "Ashley"},
{name: "Jack", children: [
{name: "Sinclair"},
{name: "Laura"}
]},
{name: "Stuart", children: [
{name: "Trevor", children: [
{name: "Woody"},
{name: "Crystal"}
]},
{name: "Allen"}
]}
]
There can be virtually unlimited levels of nesting.
What I'm trying to do: given one of the objects in this data structure, I want to add another object after it. For example, if given the name "Woody", the object I'm inserting needs to go between Woody and Crystal.
I already have a method for recursively iterating through the data structure to find an object when given a name (names are unique in this scenario). I'm just looking for a way to modify the entire data structure when something is inserted at an arbitrary location inside one of the nested arrays.
The only way I've been able to think of was to flatten the entire data structure first using JSON.stringify
, then flatten the object I'm inserting, then inserting it into the string, then converting the string back to an object. The issue with that is that JSON.stringify can be very slow for large objects, and performance is a priority here.