javascript - python : How to count all objects in an array that match a condition?

标签 javascript arrays function

如何计算数组中符合条件的所有对象: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/

相关文章:

c# - 使用 Visual Studio 2013 正则表达式查找 - 如何使多个前缀无效

javascript - 获取数组中的位置

javascript - 如何从 JavaScript 中的字符串数组中删除字符模式?

function - 将 SQL 查询转换为采用标识符的函数

javascript - React/Redux 无法读取未定义的属性 "currentOpportunities"

javascript - JSDOM + Ava – 全局依赖 `document`的测试函数

javascript - 如何将值从 Javascript 传递到第二页上的 php 变量?

arrays - 如何在 Swift 中访问二维数组中的元素

c++ - if 语句表达式调用函数,需要测试是否为真

JavaScript TypeError,无法读取未定义的属性,但函数已定义。我究竟做错了什么?