【问题标题】:How do I use lodash to check every item in a collection except those that dont meet my condition?我如何使用 lodash 检查集合中的每个项目,除了那些不符合我的条件的项目?
【发布时间】:2020-12-11 06:58:36
【问题描述】:

let allChecked = _.every(this.collection, this.checked);

如果集合中的每个项目对于checked 属性都为真,我有这个现有的代码返回真。我想修改它,而不是迭代集合中的每个项目,只迭代另一个属性上没有 true 的项目。即,对于集合中的项目,还有另一个名为 disabled 的属性。如果此属性设置为 true,我想在此 _.every() 检查中完全忽略这些项目。

【问题讨论】:

  • 您可以将谓词传递给 .every: `.every(this.collection, item => item.disabled || item.checked)

标签: javascript typescript lodash


【解决方案1】:

您只需在 this.collection 上调用 _.reject 即可删除集合中指定属性为 true 的所有项目。

例如_.every(_.reject(this.collection, 'disabled'), this.checked)

【讨论】:

    【解决方案2】:

    只需将disabled 添加到短路检查即可。如果disabledtrue 你可以跳过检查:

    let allChecked = _.every(this.collection, obj => obj.disabled || this.checked(obj));
    

    【讨论】:

      猜你喜欢
      • 2011-05-17
      • 1970-01-01
      • 2013-07-13
      • 1970-01-01
      • 2022-11-27
      • 1970-01-01
      • 1970-01-01
      • 2019-07-12
      • 1970-01-01
      相关资源
      最近更新 更多