Juntae Juntae - 3 months ago 6
Javascript Question

Get length of same key in array of javascript objects

var arr = [{code:'A', number: 1}, {code:'A', number: 2}, {code:'B', number: 3 }]


How can I get a number of objects that has certain key in above array?

For example, The number of
code: 'A'
objects is 2.

How to get it?

Answer

filter will iterate through the array and execute your callback function. The callback function needs to evaluate to a boolean for the value to return.

var arr = [{code:'A', number: 1}, {code:'A', number: 2}, {code:'B', number: 3 }]
arr.filter(function(x) { return x.code === 'A'}).length
Comments