How to smooth nested for each?

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 valuesobjects of nested arrays as follows:

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 ones forEach? (Without using any library like Lodash?)

+4
source share
4 answers

Of course, but really there is no use.

Your current data structures are such that you need to iterate through each subitem for each element in your array.

If only the nesting appearance bothers you, you can 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)
}

This suggests that there is no benefit other than personal taste.

, , , , ​​ Map Set

+3

, , , , :

updateField (name, value) {
  this.schema
    .reduce((memo, item) => [...memo, ...item.fields], [])
    .forEach(field => {
      if (field.name === name) field.value = value;
    });
}
+3

You can use a loop for..of, destructuring an object,Object.entries()

const obj = {
  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: ''
    }]
  }],
  updateField(name, value) {
    for (let [key, {fields}] of Object.entries(this.schema)) {
      for (let [index, {name: _name}] of Object.entries(fields)) {
        if (name === _name) fields[index].value = value;
      }
    }
  }
}

obj.updateField("name", 123);

console.log(obj.schema[0].fields[0]);
Run code
+1
source

I suggest introducing a generator function that facilitates field iteration:

function* fields(schema) {
  for (let group of schema) yield* group.fields;
}

function updateField(name, value) {
  for (let field of fields(schema)) {
    if (field.name === name) field.value = value
  }
}
0
source

Source: https://habr.com/ru/post/1677216/


All Articles