Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatten a nested forEach?

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?)

like image 226
alex Avatar asked Feb 04 '23 10:02

alex


2 Answers

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;
    });
}
like image 120
Eeks33 Avatar answered Feb 07 '23 13:02

Eeks33


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

like image 26
nem035 Avatar answered Feb 07 '23 13:02

nem035