What are the rules for converting? I don’t understand how exactly the second is made from the first, and that’s definitely the first part to writing a code to do this.
I would iterate over the outermost array containing A & B objects, & populate them as values for Level1 key. { "level1" : { "item1" : objectA, "item2": objectB } }
I would check if object A has children,
2.1. if it does, I would have a key-value pair like: "reference":"A's_child_identifier" added to item1’s value & would would want to do the above process again for children (which is an array of objects)
2.2. this time the children of objectA will have a key-value pair as: "A's_child_identifier" : {"item1": A.child1, "item2":A.child2}
2.3. this key-value will be appended after "level1":
But why does your original desired final object have a l4? There is only a depth of 3 from what I can see. When you attempted to manually map it out you end of with a level1, level2, and level3 properties of the main object created. Which is the correct desired outcome from the original array?
Basically the reference field identifies that a node has child items. And the child items can be found in the key denoted by value of reference.
And since it’s sort of a tree structure, there can be multiple depths.