Javascript-计算具有值的数组对象 [英] Javascript - Count array objects that have a value
本文介绍了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)
这篇关于Javascript-计算具有值的数组对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文