I have a Form class (quite a lot like this) whose form fields are dynamically set. Here's an example fieldset:
Example form object dataset
jamb_style: '',
cutouts: '',
door: {
length: '',
width: '',
thickness: '',
},
lock_bore: {
location: '',
diameter: '',
},
hinge: {
size: '',
pocket_radius: '',
backset: '',
locations: {
first: '',
second: '',
third: '',
fourth: '',
},
},
face_plate: {
length: '',
width: '',
radius: '',
},
As you can see some fields are nested and others aren't, if everything sat on one level then resetting the form would be trivial:
Trivially reset a field in a flat form object
reset() {
for (let field in this.originalData) {
this[field] = '';
}
}
However, because some of my form data are objects my reset() function looks like this:
Warning, what you are about to see may disturb you
reset() {
let data = this.originalData;
for (let key in data) {
if (typeof data[key] === 'object') {
let subData = data[key];
for (let subKey in subData) {
if (typeof subData[subKey] === 'object') {
let subDataData = data[key][subKey];
for (let subKeyKey in subDataData) {
if (typeof data[key][subKey][subKeyKey] === 'string') {
this[key][subKey][subKeyKey] = '';
}
}
}
if (typeof subData[subKey] === 'string') {
this[key][subKey] = '';
}
}
}
if (typeof data[key] === 'string') {
this[key] = '';
}
}
}
What I'd really like is a way to clean this up by making this function recursive, so that it drills down and ensures that a property is only cleared when it is not an object.
The problem is I have no idea how to proceed.
recursivefunction you claim is getting out of hand? You have not posted anything that is recursive, so, it's hard to help you with your alleged issue