var arr = [{code:'A', number: 1}, {code:'A', number: 2}, {code:'B', number: 3 }]
如何在上面的数组中获得一些具有某些键的对象?
例如,code: 'A'
个对象的数量 2 。
如何获得它?
答案 0 :(得分:1)
filter将遍历数组并执行您的回调函数。回调函数需要求值为要返回的值的布尔值。
var arr = [{code:'A', number: 1}, {code:'A', number: 2}, {code:'B', number: 3 }]
arr.filter(function(x) { return x.code === 'A'}).length
答案 1 :(得分:1)
遍历数组并将诸如count和相应数字之类的信息存储在对象结构中。
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);
&#13;