Javascript-计算具有值的数组对象

问题描述:

我得到一个返回给我的数组,我需要计算其中包含值的行

I'm getting an array returned to me and I need to count the rows that have a value in them

我尝试调用arr.length,但这给了我数组的总长度

I've tried to call arr.length but that gives me the total length of the array

var arr = [
  { id: '1', '': '' },
  { id: '2', '': '' },
  { id: '3', '': '' },
  { id: '4', '': '' },
  { id: '', '': '' },
  { id: '', '': '' },
  { id: '', '': '' }
]

结果应为4.

使用过滤器仅捕获具有值的键,并返回结果数组的长度.

Use filter to only capture keys with value, and return the resulting array's length.

var arr = [ { id: '1', '': '' },{ id: '2', '': '' },{ id: '3', '': '' },{ id: '4', '': '' },{ id: '', '': '' },{ id: '', '': '' },{ id: '', '': '' },{ id: '', '': '' },{ id: '', '': '' },{ id: '', '': '' },{ id: '', '': '' },{ id: '', '': '' },{ id: '', '': '' },{ id: '', '': '' },{ id: '', '': '' },{ id: '', '': '' },{ id: '', '': '' },{ id: '', '': '' },{ id: '', '': '' },{ id: '', '': '' },{ id: '', '': '' } ]

var res = arr.filter(val => {
    return val.id
})
console.log(res.length)