【问题标题】:Count based on field flag - How to do this in Lodash基于字段标志的计数 - 如何在 Lodash 中执行此操作
【发布时间】:2017-09-19 01:53:39
【问题描述】:

我有一个包含一些对象的数组。我想知道这个数组中有多少元素将“有效”字段设置为 true。

这是我现在的代码:

1) 数组元素对象:

export class Record {
  public accuracy: string;
  public executed: boolean;
  public effective: boolean;
}

2) 数组:

public records: Array<Record>;

3)计算部分(这是我想知道如何使用Lodash改进的部分)

  let sum: number = 0;
  for (const record of this.records) {
    if (record.effective) {
      sum++;
    }
  }

从上面的代码可以看出,我打算做的是计算数组中“有效”字段设置为 true 的元素总数。

如何在 Lodash 中做到这一点?谢谢。

【问题讨论】:

  • 可能只是 this.records.filter(record =&gt; record.effective).length 但不使用 lodash

标签: arrays typescript lodash


【解决方案1】:

您可以使用lodash#filter 保留effective 对象,然后使用lodash#size 获取effective 对象的数量。

var result = _(records).filter('effective').size();

var records = [
  { effective: true },
  { effective: true },
  { effective: false },
  { effective: true },
  { effective: false },
  { effective: true },
];

var result = _(records).filter('effective').size();
  
console.log(result);
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"&gt;&lt;/script&gt;

【讨论】:

    【解决方案2】:

    您可以使用 pullAllWith 获得更干净的代码,如下所示

    let effectiveRecords =<Record[]> _.pullAllWith(this.records,{effective : 'true'}, _.isEqual);
    

    计数将来自

    effectiveRecords.length
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-03
      • 2011-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-29
      相关资源
      最近更新 更多