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

时间:2018-08-01 08:08:13

标签: javascript arrays reactjs object

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

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

所有(notes.length)2已完成(?)0未完成(?)0

4 个答案:

答案 0 :(得分:3)

使用filter

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

或使用reduce

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

答案 1 :(得分:2)

您可以使用filter()减少对象数组中的记录,并找到存在的记录的长度,其行为与SQL查询中的where相似。您可以向数组中存在的任何 key 添加条件。

completed = state.notes.filter(x=>x.Completed==true).length; incomplete = state.notes.filter(x=>x.Completed==false).length;

答案 2 :(得分:1)

您可以过滤完成的笔记,然后检查长度:

const completedNotes = notes.filter((note) => note.completed)


completedNotes.length

这对您有帮助吗?

答案 3 :(得分:0)

可以使用reduce来实现。

var a = {
  text: '',
  notes: [
     {todo: "hello", completed: true},
     {todo: "world", completed: false},
     {todo: "hello", completed: true},
     {todo: "world", completed: false},
     {todo: "hello", completed: true},
     {todo: "world", completed: false},
     {todo: "hello", completed: true},
     {todo: "world", completed: true}
  ]
};


let count = a.notes.reduce((b,n)=>{
  if (n.completed)
      b.x.push(n);
  else
      b.y.push(n)
  return b;
}, {x:[], y:[]});

console.log(count.x.length + ' ' + count.y.length);

使用reduce遍历notes数组,传递一个空对象作为reduce的参数(此对象应包含完成的和未完成的键)从reduce返回新对象,并将length属性应用于该数组,您将获得长度两者。

jsbin:http://jsbin.com/jokayuxuvo/edit?js,console