Javascript - Count array objects that have a value

后端 未结 8 608
情话喂你
情话喂你 2021-01-19 01:52

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

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

8条回答
  •  臣服心动
    2021-01-19 02:44

    Use reduce to add the items up if id.length > 0

    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: '', '': '' } ]
    
    
    let count = arr.reduce((val, itm) => itm.id.length > 0 ? val + 1 : val + 0, 0)
    
    console.log(count)

提交回复
热议问题