I have form inputs that are generated based off an XML file.
We keep a reference of nested elements in the XML file via data-* attributes which can later be used to build an object. For example:
<parent>
<child>
<grandchild1>first</grandchild1>
<grandchild2>second</grandchild2>
</child>
</parent>
Becomes
<input type="text" data-nest="parent.child.grandchild1" value="first"/>
<input type="text" data-nest="parent.child.grandchild2" value="second"/>
When we submit the form, I create an object (with nested objects) based off of their data-nest attribute. The above would become
parent:{
child:{
grandchild1: first,
grandchild2: second
}
}
The issue that I am running into is where multiple of the same tag are found in the XML file, e.g.
<child>
<grandchild>first</grandchild>
<grandchildFriend>firstFriend</grandchildFriend>
</child>
<child>
<grandchild>second</grandchild>
<grandchildFriend>secondFriend</grandchildFriend>
</child>
When I create my object, I would like it so that if multiple occurrences of the same data-nest value are found, they are nested inside of an array in order to maintain the different values.
With the current setup, the second occurrence of the tag will understandably overwrite the first.
This is the final object structure I desire:
parent:{
child:[
{
grandchild: first,
grandchildFriend: firstFriend
},
{
grandchild: second,
grandchildFriend: secondFriend
}
]
}
TL;DR
I'd like to change an object to an array of nested objects if they have the same data-* attribute
Here's a fiddle of how the current code works to help give a better understanding.