简体   繁体   中英

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?

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

Iterate through the array and store the informations like count and corresponding numbers in an object structure.

 var arr = [{code:'A', number: 1}, {code:'A', number: 2}, {code:'B', number: 3 }]; var obj = {}; debugger; for (var i =0, len = arr.length; i < len; i += 1) { ele = arr[i]; code = ele.code if (!obj[code]) { obj[code] = { count: 0, number: [] }; } obj[code].count += 1; obj[code].number.push(ele.number); } function getCount(code) { return obj[code].count; } console.log(getCount('A')); // 2 console.log(getCount('B')); // 1 console.log(obj); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM