如何计算数组中符合条件的所有对象:is_read == true
?
这就是我的数组的样子:
[
{
"id": 1,
"is_read": true,
},
{
"id": 2,
"is_read": true,
},
{
"id": 3,
"is_read": false,
},
{
"id": 4,
"is_read": true,
},
]
最佳答案
只需使用 filter
通过传递 callback
的方法功能与用途length
用于过滤结果的属性。
let data = [ { "id": 1, "is_read": true, }, { "id": 2, "is_read": true, }, { "id": 3, "is_read": false, }, { "id": 4, "is_read": true, }, ],
length = data.filter(function(item){
return item.is_read;
}).length;
console.log(length);
您也可以使用
lambda
表达。 let data = [ { "id": 1, "is_read": true, }, { "id": 2, "is_read": true, }, { "id": 3, "is_read": false, }, { "id": 4, "is_read": true, }, ],
length = data.filter(d => d.is_read).length;
console.log(length);
关于javascript - python : How to count all objects in an array that match a condition?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47923254/