我有一个对象数组,每个对象都有一个状态属性,它可能是通过或失败或跳过。如果对象状态不是'通过',那么我必须设置数组状态失败而不管对象的数量在数组和不相关的状态传递对象。
singleTestMethod=[
{'status':'PASS'},
{'status':'PASS'},
{'status':'FAIL'},
{'status':'SKIPPED'},
'arrayStatus':'']
我希望只有当数组中的所有对象状态都通过时才应设置数组状态,否则应将其设置为仅失败。
据我所知,您想知道所有对象是否具有传递状态,否则它被视为失败对吗?
然后:
const testArr1 = [
{status:'PASS'},
{status:'PASS'},
{status:'FAIL'},
{status:'SKIPPED'},
{arrayStatus:''}]
const testArr2 = [
{status:'PASS'},
{status:'PASS'}]
const checkArray = (testArr) => !testArr.find(each => each.status !== 'PASS')
console.log(checkArray(testArr1)) // false
console.log(checkArray(testArr2)) // true
我认为你在编写阵列时写了一个拼写错误,我自由地修复了它。
由于您的请求缺乏明确性,我还假设您的结构始终相同,因此'arrayStatus'将是数组的最后一项。
我的理解是你要检查数组中的所有'status'值。
如果所有都是'PASS',那么'arrayStatus'也必须变为'PASS',否则'arrayStatus'必须变为'FAIL'。
如果上述假设是正确的,请尝试以下代码:
var singleTestMethod=[
{'status':'PASS'},
{'status':'PASS'},
{'status':'FAIL'},
{'status':'SKIPPED'},
{'arrayStatus':''}];
console.log("singleTestMethod array before its check:")
console.log(singleTestMethod);
function setArrayStatus(myArray){
var totalItems = myArray.length - 1;
var totalPass = 0;
myArray.forEach(function(entry) {
if (entry.status === "PASS"){
totalPass++;
}
});
if (totalItems === totalPass){
myArray[myArray.length - 1] = {'arrayStatus': 'PASS'};
} else {
myArray[myArray.length - 1] = {'arrayStatus': 'FAIL'};
}
return myArray;
}
singleTestMethod = setArrayStatus(singleTestMethod);
console.log("singleTestMethod array after its check:")
console.log(singleTestMethod);
感谢您的回答,我已尝试使用对象过滤器属性如下..
var singleTestMethod = [
{'status':'PASS'},
{'status':'FAIL'},
{'status':'SKIPPED'},
{'arrayStatus':''}];
const result = singleTestMethod.filter(singleTestMethod =>
singleTestMethod.status === 'FAIL' || singleTestMethod.status === 'SKIPPED');
console.log(result);
if(result.length == 0){
singleTestMethod.arrayStatus = 'PASS';
}else{
singleTestMethod.arrayStatus = 'FAIL';
}
console.log( singleTestMethod.arrayStatus);