我有不同对象的数组,如下所示:
[{
color:'red',
'type':'2',
'status':'true'
}
{
color:'red',
'type':'2',
'status':'false'
}]
我想过滤像status
这样的元素,然后计算过滤后的内容,例如,如果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);
}
答案 0 :(得分:3)
如果我理解正确,您想要计算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);
答案 1 :(得分:3)
好吧,你可以做一个计数,或者你可以运行一个过滤器并获得最终数组的长度。
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 );
答案 2 :(得分:0)
仅添加最新语法和更具可读性的IMO:
const items = [
{ color:'red', type:'2', status:'true' },
{ color:'red', type:'2', status:'false' }
];
const statusFalseCount = items.filter(e => e.status === 'false').length;
console.log(statusFalseCount); // => 1