如何拼合嵌套forEach?

亚历克斯

我有以下输入:

 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: ''
    }]
  }],

然后我这样设置values嵌套数组的对象:

updateField (name, value) {
  this.schema.forEach((formGroup, index) => {
    formGroup.fields.forEach(field => {
      if (field.name === name) field.value = value
    })
  })
},

有没有办法避免使用两个嵌套forEach(是否不使用Lodash等任何库?)

nem035

可以,但是并没有真正的好处。

当前的数据结构使得您需要遍历数组中每个项目的每个子项目。

如果仅嵌套的外观困扰您,则可以分离功能。

updateField (name, value) {
  const updateFormGroupField = field => {
     if (field.name === name) field.value = value;
  };

  const updateFormGroup = formGroup => formGroup.forEach(updateFormGroupField);

  this.schema.forEach(updateFormGroup)
}

话虽这么说,除了个人口味,这里真的没有任何好处。

也许更好的焦点是看如何使用常量访问结构(例如aMap或a)来降低这些嵌套操作的二次复杂度Set

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章