-1

Hi guys iam trying to find the count of a specified field if its present inside a object of array For example

[{name:'Linus',rate:'23'},{name:'Sebastin'},{name:'Alex',rate:''}] 

what iam trying to achieve is count the number of key 'rate' inside the object

iam expecting a output like

2

2 Answers2

2

You can use reduce to iterate the input data and count the number of times the key occurs in one of the objects:

data = [{name:'Linus',rate:'23'},{name:'Sebastin'},{name:'Alex',rate:''}] 

const countKeys = (data, key) => data.reduce((acc, o) => acc + (key in o), 0)

console.log(countKeys(data, 'rate'))
Nick
  • 138,499
  • 22
  • 57
  • 95
1

var data = [{name:'Linus',rate:'23'},{name:'Sebastin'},{name:'Alex',rate:''}];
var count = 0;
var key ='rate';
data.forEach(d =>{
  if(d.hasOwnProperty(key)){
    count++;
   }
});
console.log(count);

A reference for you how-do-i-check-if-an-object-has-a-specific-property-in-javascript

flyingfox
  • 13,414
  • 3
  • 24
  • 39