My task requires me to convert specific form fields that contain "object nesting" in the field names back to the objects themselves. Here are some examples of typical form field names:
- phones_0_patientPhoneTypeId
- phones_0_phone
- phones_1_patientPhoneTypeId
- phones_1_phone
The form fields above were extracted from an object similar to the one shown below (refer to "Data"). The format of the object needs to be reconstructed. Any form field with an underscore _ character in its name should undergo this conversion. Additionally, if the segment between underscores in the form field name is numeric, it represents a JavaScript array; otherwise, it signifies an object.
I managed to come up with a basic implementation for flattening the original object for form use, but I am facing challenges with reversing the process. Below the object/data section, I have included my current attempt at achieving this. One issue with my implementation is that it does not handle array indexes correctly, which could be problematic when encoding the object as JSON, especially considering sparse arrays. For example, even if "phones_1" exists and "phones_0" does not, I still want to ensure that a slot exists for phones[0] even if the value is null.
Data:
var obj = {
phones: [{
"patientPhoneTypeId": 4,
"phone": "8005551212"
},
{
"patientPhoneTypeId": 2,
"phone": "8885551212"
}
]
};
Current Code:
var unflattened = {};
for (var prop in values) {
if (prop.indexOf('_') > -1) {
var lastUnderbarPos = prop.lastIndexOf('_');
var nestedProp = prop.substr(lastUnderbarPos + 1);
var nesting = prop.substr(0, lastUnderbarPos).split("_");
var nestedRef, isArray, isObject;
for (var i = 0, n = nesting.length; i < n; i++) {
if (i === 0) {
nestedRef = unflattened;
}
if (i < (n - 1)) { // not last
if (/^\d+$/.test(nesting[i + 1])) {
isArray = true;
isObject = false;
} else {
isArray = true;
isObject = false;
}
var currProp = nesting[i];
if (!nestedRef[currProp]) {
if (isArray) {
nestedRef[currProp] = [];
} else if (isObject) {
nestedRef[currProp] = {};
}
}
nestedRef = nestedRef[currProp];
} else {
nestedRef[nestedProp] = values[prop];
}
}
}