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

新手上路,请多包涵

我有一组不同的对象,看起来像这样:

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

我想过滤像 status 这样的一个元素,然后对过滤后的元素进行计数,例如,如果状态为假,则返回 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);
}

原文由 DEO 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 300
2 个回答

好吧,你可以只做一个计数,或者你可以运行一个过滤器并获得最终数组的长度。

 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 );

原文由 Tim Consolazio 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果我理解正确,你想计算元素的数量,其中 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);

原文由 taguenizy 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题