Reputation: 45
I wish to increment variables if a condition is true.
I have a object that has info like
{id: 1, payment: pending}
{id: 2, payment: paid}
Here is what I have done so far:
var currentIndex = 0;
$scope.unpaid = 0;
$scope.paid = 0;
const getSessions = () => {
loginService.getUser().then((response) => {
var user_id = response.data.id;
console.log("getUser returning this => ", response.data);
loginService.getUserSessions(user_id).then((response) => {
var sessions = response.data;
console.log(sessions);
sessions.forEach(e => e.next_class = e.next_class.substring(0, 10));
sessions.forEach(function (arrayItem) {
if(arrayItem.payment === "Pending") {
$scope.unpaid++;
}else{
$scope.paid++;
};
});
$scope.new = sessions;
Date($scope.class).toISOString().slice(0,10);
})
})
};
getSessions();
I can loop in the object using the for each
, but I want to loop through the object and check the payment
key. If payment == pending
store in unpaid
, and if payment == paid
then store in paid
.
The front end would show how many unpaid sessions and paid there are displayed in numbers, for example:
Unpaid 1
Paid 1
Upvotes: 1
Views: 315
Reputation: 6394
I am assuming the objects are in an array, I'll also assume it is called payments
:
var paid = 0;
var unpaid = 0;
var payments = [{id: 1, payment: 'paid'}, {id: 2, payment: 'unpaid'}, {id: 3, payment: 'unpaid'}];
for (var payment in payments) { // iterate through all payments
if (payments[payment].payment == 'paid') { // if the person has paid
paid++; // count a payment
} else { // if the person hasn't paid
unpaid++; // count a non-payment
}
}
console.log("Paid: " + paid + ", Unpaid: " + unpaid);
Also, you should probably make payment
a boolean, and call it paid
, where true means the person has paid, false means not paid.
If you do that, then you can change the if condition to say if (payments[payment].paid) { ... }
. Much nicer!
Upvotes: 1