在Javascript中过滤对象数组并计算过滤后的元素数量

9

我有一个由不同对象组成的数组,形式如下:

[{
   color:'red',
   'type':'2',
   'status':'true'
 }
 {
   color:'red',
   'type':'2',
   'status':'false'
 }]

我希望过滤一个名为status的元素,然后统计过滤后的数量,例如,如果状态为false,则返回1。

我已经尝试了下面的代码,但我不确定我在这里做什么:

for (i = 0; i < check.length; i++) {
  var check2;

  console.log(check[i].isApproved);
  (function(check2) {
    return check2 = check.filter(function(val) { 
        return val == false 
    }).length;
  })(check2)

  console.log('again Rides',check2);
}

1
需要进一步解释。单词“filtered”被过度使用了。这非常不清楚... - IronAces
3个回答

24
如果我理解正确,您想计算status等于'false'的元素数量。注意:您在status中拥有的值是字符串。

var check = [
  { color:'red', 'type':'2', 'status':'true' }, 
  { color:'red', 'type':'2', 'status':'false' } 
];

var countfiltered = check.filter(function(element){
    return element.status == 'false';
}).length

console.log(countfiltered);


使用最新的JS特性更新:const countfiltered = check.filter((c) => c.status === "false").length; - jarmod


4

你可以进行计数,或者运行筛选器并获取最终数组的长度。

var count = 0;
var arr = [{color:'red', type:'2', status:'true'},
           {color:'red', type:'2', status:'false'} ];
// Showing filterin to be robust. You could just do this in 
// a loop, which would be sensible if you didn't need the subarray. 
var filtered = arr.filter ( function ( d ) {
    // Note that I'm testing for a string, not a boolean, because
    // you are using strings as values in your objects. 
    // If it was a boolean, you'd use if ( d.status ) { ... }
    count++;
    return d.status === 'false';
});

// These should be the same, reflecting number of objs with 'false'
console.log ( count );
console.log ( filtered.length );
// This should trace out a sub array of objs with status === 'false'
console.log ( filtered );

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接