I have a nested object:
const refsObject = {
refOne: {
current: {
validate: function()
}
},
refTwo: {
current: {
validate: function()
}
}
};
I need to run input field validation using a single method that loops through each nested object of objects and invokes the validate method .
What I have tried up until now:
const splitObject = o => Object.keys(o).map(e => ({ [e]: o[e] }));
splitObject.forEach(ref => ref.current && ref.current.validate());
SplitObject returns me an array of objects with all the objects inside refsObject
. Once I do forEach on splitObject it becomes undefined since ref.current is inside the nested object key " refOne " which is dynamic so I cannot hardcode. Any suggestion helps!
Run the validations on the original refsObject
by taking the values, and iterating them with Array.forEach()
. Use conditional chaining ?.
to call the function in case current
might be undefined
:
const refsObject = {refOne:{current:{validate(){console.log('refOne')}}},refTwo: {current: {validate() {console.log('refTwo')}}}}; const runValidations = o => Object.values(o).forEach(ref => ref.current?.validate()); runValidations(refsObject);
Is this what you're looking for?
const refsObject = { refOne: { current: { validate: function() { console.log('validate1'); } } }, refTwo: { current: { validate: function() { console.log('validate2'); } } } }; Object.values(refsObject).map(refs => refs.current.validate());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.