Hi i am trying to find the sum of Boolean values in the object array in JavaScript
您好我试图在JavaScript中找到对象数组中的布尔值的总和
My json like be
我的json喜欢
var myoBj = [{
"id": 1,
"day": 1,
"status": true
}, {
"id": 2,
"day": 1,
"status": false
}, {
"id": 3,
"day": 1,
"status": false
}, {
"id": 4,
"day": 3,
"status": false
}];
i want the sum of all status values using reduce function in JavaScript/ typescript
我希望使用JavaScript / typescript中的reduce函数来计算所有状态值的总和
i want to show overall status as true only when all status are true else it should be false
我希望只有当所有状态都为真时才显示整体状态为真,否则它应该为假
2 个解决方案
#1
8
var result = myObj.reduce((sum, next) => sum && next.status, true);
This should return true, if every value is true.
如果每个值都为真,则返回true。
#2
5
If you want to sum lets say, day
items value depending on the status
flag, this can looks like:
如果你想总结,可以说,日期项目值取决于状态标志,这可能看起来像:
var result = myObj.reduce((res, item) => item.status ? res + item.day : res, 0);
Update 1
For overall status in case of all statuses are true you should use every method:
对于所有状态均为true的整体状态,您应该使用每种方法:
var result = myObj.every(item => item.status);
#1
8
var result = myObj.reduce((sum, next) => sum && next.status, true);
This should return true, if every value is true.
如果每个值都为真,则返回true。
#2
5
If you want to sum lets say, day
items value depending on the status
flag, this can looks like:
如果你想总结,可以说,日期项目值取决于状态标志,这可能看起来像:
var result = myObj.reduce((res, item) => item.status ? res + item.day : res, 0);
Update 1
For overall status in case of all statuses are true you should use every method:
对于所有状态均为true的整体状态,您应该使用每种方法:
var result = myObj.every(item => item.status);