![](/img/trans.png)
[英]How to validate with Yup that in array of objects at least one of object keys has true value?
[英]every object should have at least one true property value in array of objects?
我想創建一個返回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())
可以使用Array#some
const Items = [{ parentValidators: [{ isValid: true }, { isValid: false }, { isValid: false }] }, { parentValidators: [{ isValid: false }, { isValid: false }, { isValid: false }] } ] const res = Items.map(({parentValidators:v})=> v.some(({isValid:i})=>i)) console.log(res)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.