Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Count Of a specific key if present inside a object of array [JavaScript]

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

2

>Solution :

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'))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading