我想创建一个返回 true 的函数(每个对象应该至少有一个 isValid:true
),否则返回 false。
const Items = [{
parentValidators: [{
isValid: true
}, {
isValid: false
}, {
isValid: false
}]
},
{
parentValidators: [{
isValid: true
}, {
isValid: false
}, {
isValid: false
}]
}
]
// i tried :
validateSection() {
Items.map(item => {
if (item.parentValidators) {
const logs = item.parentValidators;
return logs.map(l => {
return l.isValid ? true : l.isValid;
});
}
}).map((i, indx, arr) => {
let count = 0;
if (i.includes('true')) {
count++;
}
return count === array.length ? true : false;
})
}
最佳答案
如果 Items
中的每一项都至少有一个 isValid
值为 true
的验证器,则返回 true 的函数是完美的用例对于数组 every
和 some
方法的组合:
const Items = [{
parentValidators: [{
isValid: true
}, {
isValid: false
}, {
isValid: false
}]
},
{
parentValidators: [{
isValid: true
}, {
isValid: false
}, {
isValid: false
}]
}
]
// i tried :
function validateSection() {
return Items.every(validators => validators.parentValidators.some(i => i.isValid));
}
console.log(validateSection())
关于javascript - 每个对象在对象数组中都应该至少有一个真实的属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48212508/