我在数据库中有一个数据,如下所示
vm.result = [
{
"_id": ObjectId("57c036a75f7635e80c5d5bc8"),
"sharedPersonId": ObjectId("570dec75cf30bf4c09679deb"),
"notificationDetails": [
{
"userId": "570dfae0e79bd384255b6471",
"userName": "Vinay",
"isRed": true
}
]
},
{
"_id": ObjectId("57bef418600b4350280f0b2f"),
"sharedPersonId": ObjectId("570dec75cf30bf4c09679deb"),
"notificationDetails": [
{
"userId": "56fe44836ce2226431f5388f",
"userName": "Hemanth",
"isRed": true
}
]
},
{
"_id": ObjectId("57bef1a1d985a82c24e0c49b"),
"sharedPersonId": ObjectId("570dec75cf30bf4c09679deb"),
"notificationDetails": [
{
"userId": "57443657ee5b5ccc30c4e6f8",
"userName": "Kevin",
"isRed": true
}
]
}
]
要访问isRed,我在angular.js文件中使用了循环,如下所示
for(var key in vm.result){
for(var key1 in vm.result[key].notificationDetails){
console.log(vm.result[key].notificationDetails[key1].isRed);
}
}
结果显示为真
真正
真正
isRed包含true
和false
的可能性。我想知道有多少真实的东西。
如何解决这个请帮助我。
答案 0 :(得分:2)
var trueCount = 0;
var falseCount = 0;
for(var key in vm.result){
for(var key1 in vm.result[key].notificationDetails){
if(vm.result[key].notificationDetails[key1].isRed){
trueCount ++ ;
}else{
falseCount ++;
}
}
}
通过这种方式,您可以跟踪真实和虚假的内容。
答案 1 :(得分:2)
Writes
答案 2 :(得分:2)
function countResult(vm) {
var total = 0;
vm.result.forEach(function(item) {
total += countNotifications(item.notificationDetails);
});
return total;
}
function countNotifications(notifications) {
var count = 0;
notifications.forEach(function(notification) {
count += (notification.isRed ? 1 : 0)
});
return count;
}
答案 3 :(得分:2)
var isRedCount = vm.result.reduce(
(c, res) => c + res.notificationDetails.filter(d => d.isRed).length
, 0);
var vm = {};
vm.result = [{
"_id": "57c036a75f7635e80c5d5bc8",
"sharedPersonId": "570dec75cf30bf4c09679deb",
"notificationDetails": [{
"userId": "570dfae0e79bd384255b6471",
"userName": "Vinay",
"isRed": true
}]
}, {
"_id": "57bef418600b4350280f0b2f",
"sharedPersonId": "570dec75cf30bf4c09679deb",
"notificationDetails": [{
"userId": "56fe44836ce2226431f5388f",
"userName": "Hemanth",
"isRed": true
}]
}, {
"_id": "57bef1a1d985a82c24e0c49b",
"sharedPersonId": "570dec75cf30bf4c09679deb",
"notificationDetails": [{
"userId": "57443657ee5b5ccc30c4e6f8",
"userName": "Kevin",
"isRed": true
}]
}];
var isRedCount = vm.result.reduce(
(c, res) => c + res.notificationDetails.filter(d => d.isRed).length, 0);
console.log('isRedCount', isRedCount);