javascript - 如何 forEach where (angular.js)

标签 javascript arrays angularjs foreach push

在这个 forEach 中,我将一些字段插入现有数组中。 我如何过滤掉 prop.isRequired = false 的位置?

所以:(仅)循环 schema.properties 中的所有内容,其中 isRequired = true;

 angular.forEach(vm.schema.properties, function (prop,key) {
   vm.mappingFields.push({      //this is an array
     source: null,                //this gets pushed
     destination: key,            //this gets pushed
     fieldType: prop.type,        //this gets pushed
     isRequired: prop.isRequired, //this gets pushed
   });
 });

最佳答案

我会用现代的方式做到这一点,如下所示:

  vm.mappingFields = vm.schema.properties.filter({ isRequired } => isRequired).map(prop => {
      source: null,
      destination: key,
      fieldType: prop.type,
      isRequired: prop.isRequired
  })

首先,我们使用 ES6 Array.filter 方法,然后使用 Array.map 生成具有所需字段的新数组,并将新生成的数组分配给 vm.mappingFields.

我还使用 ES6 解构 { isRequired } => isRequired 来减少代码 (prop => prop.isRequired) 并使其更易于阅读。

还有一件事是,当您生成新数组时, isRequired: prop.isRequired 是不必要的,因为我们知道只有具有 isRequired: true 的元素才会来到这里..所以我将其更改为 isRequired: true

<小时/>

当然,您可以像其他贡献者提到的那样使用 forEachif 条件获得相同的结果,但这并不像我的答案那么优雅。但说实话,我的方法需要稍微多一点的时间来完成 2 个数组周期的评估,但请记住我们为人类编写代码,而不是为机器编写代码。

关于javascript - 如何 forEach where (angular.js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54344334/

相关文章:

javascript - sequelize findOrCreate 不返回数组

javascript - TypedJS 错误 : Uncaught ReferenceError: Typed is not defined

Java特殊数组补顶/覆盖

java - 如何在 MySQL Workbench 中存储 10x10 map /游戏字段?

angularjs - Linux Azure Web 应用程序上的 node.js 部署出错

javascript - 在 :visited , 中只有一项更改有效

javascript - Mustache html 模板的安全问题

c - 二分查找 C

javascript - AngularJs json-formatter json 属性作为范围变量

javascript - 通过 .scope().call() 从 JS 外部调用 Angular 服务挂起请求