I have the following input:
schema: [{
fields: [{
name: 'name',
type: 'text',
col: 10,
value: ''
}, {
name: 'description',
type: 'text',
col: 2,
value: ''
}]
}, {
fields: [{
name: 'password',
type: 'text',
col: 8,
value: ''
}, {
name: 'confirmPassword',
type: 'textarea',
col: 4,
value: ''
}]
}],
And I set the values
of the objects of the nested arrays like this:
updateField (name, value) {
this.schema.forEach((formGroup, index) => {
formGroup.fields.forEach(field => {
if (field.name === name) field.value = value
})
})
},
Is there a way to avoid using two nested forEach
? (Without using any library like Lodash?)
You can flatten your array using reduce and the spread operator to combine your arrays, then forEach over your flat array:
updateField (name, value) {
this.schema
.reduce((memo, item) => [...memo, ...item.fields], [])
.forEach(field => {
if (field.name === name) field.value = value;
});
}
Sure but there isn't really a benefit to it.
Your current data structures are such that you are required to iterate over each subitem for each item in your array.
If only the appearance of nesting bothers you, you could separate the functions.
updateField (name, value) {
const updateFormGroupField = field => {
if (field.name === name) field.value = value;
};
const updateFormGroup = formGroup => formGroup.forEach(updateFormGroupField);
this.schema.forEach(updateFormGroup)
}
That being said, there isn't really any benefit here other than personal flavor.
Perhaps a better focus would be to see how to reduce the quadratic complexity of these nested operations using a constant access structure like a Map
or a Set
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With