在这个 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
当然,您可以像其他贡献者提到的那样使用 forEach
和 if
条件获得相同的结果,但这并不像我的答案那么优雅。但说实话,我的方法需要稍微多一点的时间来完成 2 个数组周期的评估,但请记住我们为人类编写代码,而不是为机器编写代码。
关于javascript - 如何 forEach where (angular.js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54344334/