我有一个包含一些对象的数组。我想知道这个数组中有多少个元素的字段“有效”设置为真。
下面是我的代码:
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的元素总数。
在洛达什怎么做?谢谢。
发布于 2017-04-22 00:18:06
您可以使用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);<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
发布于 2017-04-22 02:31:03
您可以使用pullAllWith来获得更清晰的代码,如下所示
let effectiveRecords =<Record[]> _.pullAllWith(this.records,{effective : 'true'}, _.isEqual);伯爵将来自
effectiveRecords.lengthhttps://stackoverflow.com/questions/43553257
复制相似问题