javascript - 如何根据 obj 标志的状态查找数组长度

标签 javascript arrays reactjs object

我有一系列待办事项,我试图显示已完成的未完成待办事项的数量。我知道我可以执行 array.length 并且可以找到总数量,但在这种情况下我是堆栈。

this.state = {
  text: '',
  notes: [
     {todo: "hello", completed: true},
     {todo: "world", completed: false}
  ]
}

全部(notes.length) 2 已完成(?) 0 未完成(?) 0

最佳答案

使用过滤器

let completedCount = this.state.notes.filter(n => n.completed).length;
let incompleteCount = this.state.notes.length - completedCount;

或使用减少

let result = this.state.notes.reduce( (acc, curr) => {
   if(curr.completed) acc.complete++;
   else acc.incomplete++;
   return acc;
}, {complete:0,incomplete:0});
console.log(result.complete); // 1
console.log(result.incomplete); // 1

关于javascript - 如何根据 obj 标志的状态查找数组长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51628337/

相关文章:

arrays - OCaml - int 数组和垃圾回收

java - JLabel的显示数组

javascript - 在 UIManager 中找不到 RNCSafeAreaView

python - 如何找到列表中不一定相邻的最大连续数字集?

javascript - 数据表,更改 AJAX 数据(不使用元素)

javascript - Angular2 中两个组件干扰文件事件

javascript - 如何在 angularjs 中编写返回 promise 的异步方法?

reactjs - 表单输入的值在 React 中提交时未更新

reactjs - 将表单与 MUI onSubmit 方法一起使用不起作用

javascript - 在 cakePHP 中更改 Flash 警报