简体   繁体   English

如何检查 Typescript 对象数组中的多个值?

[英]How to check multiple values within an array of Typescript objects?

I am storing a number of objects within the below array in my Typescript project我在 Typescript 项目的以下数组中存储了许多对象

(I have removed some data to make the code easier to read) : (我删除了一些数据以使代码更易于阅读)

workoutExercises = [
    {
      id: 0,
      exerciseComplete: false,
    },
    {
      id: 1,
      exerciseComplete: false,
    },
    {
      id: 2,
      exerciseComplete: false,
    },
  ];

I am trying to write some code that checks if all the exerciseComplete vaues are TRUE .我正在尝试编写一些代码来检查所有exerciseComplete完成值是否为TRUE

If all of them are TRUE , I want to perform a certain action.如果所有这些都是TRUE ,我想执行某个操作。 If at least one of them is FALSE , I want to perform a different action.如果其中至少一个是FALSE ,我想执行不同的操作。

I'm able to loop through the objects with the below For Loop, but I'm not sure how to check all the exerciseComplete values.我可以使用下面的 For 循环遍历对象,但我不确定如何检查所有的exerciseComplete值。

for (let i = 0; i < this.workoutExercises.length; i++) {
    console.log(this.workoutExercises[i].exerciseComplete);
}

Can someone please tell me how I would check the above with this loop?有人可以告诉我如何用这个循环检查上面的内容吗?

Use Array.every() .使用Array.every()

workoutExercises.every(exercise => exercise.exerciseComplete)

//returns true if all exercises are complete

Array.every() will help you check whether all elements in the array pass or not Array.every() 将帮助您检查数组中的所有元素是否通过

The every() method tests whether all elements in the array pass the test implemented by the provided function. every() 方法测试数组中的所有元素是否通过提供的函数实现的测试。 It returns a Boolean value.它返回一个布尔值。

const isBelowThreshold = (currentValue) => currentValue < 40;

const array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.every(isBelowThreshold));
// expected output: true

Array.every() Array.every()

if (workoutExercises.some(item => !item.exerciseComplete)) {
    //...
} else {
    //...
}

Create an array copy where excercises are complete and then compare both sizes创建一个数组副本,其中练习完成,然后比较两个大小

let workoutExercisesDone = workoutExercises.filter(exercise => exercise.exerciseComplete); //this will filter yout array by exercises finished

then compare if both lenght are equals然后比较两个长度是否相等

workoutExercisesDone == workoutExercises //true means that all exercises are done

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

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