简体   繁体   English

查找布尔值的总和 JavaScript 对象数组

[英]find sum of Boolean values JavaScript object array

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/打字稿中使用 reduce 函数的所有状态值的总和

i want to show overall status as true only when all status are true else it should be false我想仅当所有状态都为真时才将整体状态显示为真,否则它应该为假

var result = myObj.reduce((sum, next) => sum && next.status, true);

如果每个值都为真,这应该返回真。

If you want to sum lets say, day items value depending on the status flag, this can looks like:如果您想根据status标志对day项目值进行求和,则如下所示:

var result = myObj.reduce((res, item) => item.status ? res + item.day : res, 0);

Update 1更新 1

For overall status in case of all statuses are true you should use every method:对于所有状态都为真的整体状态,您应该使用每种方法:

var result = myObj.every(item => item.status);

You could use Array.some with predicate a => !a.status or Array.every with predicate a => a.status .您可以将Array.some与谓词a => !a.statusArray.every与谓词a => a.status

Either of them will short-circuit if you find a mismatch, while Array.reduce will not.如果您发现不匹配,它们中的任何一个都会短路,而Array.reduce不会。

If you must use reduce you can take advantage of the fact that x*false == 0 , and so you can do the following:如果您必须使用reduce您可以利用x*false == 0的事实,因此您可以执行以下操作:

 const 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}], res = !!myObj.reduce((bool, {status}) => bool*status, true); console.log(res);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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