【问题标题】:every object should have at least one true property value in array of objects?每个对象都应该在对象数组中至少有一个真正的属性值?
【发布时间】:2018-06-21 02:29:59
【问题描述】:

我想创建一个返回 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;
  })

}

【问题讨论】:

    标签: javascript jquery reactjs ecmascript-6


    【解决方案1】:

    如果Items 中的每个项目都至少有一个isValid 值为true 的验证器,则返回true 的函数是数组everysome 方法组合的完美用例:

    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())

    【讨论】:

      【解决方案2】:

      可以使用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)

      【讨论】:

        猜你喜欢
        • 2021-04-17
        • 1970-01-01
        • 2014-03-28
        • 2021-12-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多