简体   繁体   中英

How can I check if an object has an empty value on a key?

I am working on a form validation and I need to check when there is an empty value.

So far the validation goes like this:

const areFieldsFilledOut = () => {
    if (
      (size(startupThirdStepForm) === 9 &&
        !has(startupThirdStepForm, 'middleName')) ||
      size(startupThirdStepForm) === 10
    ) {
      stepThreeCardSelectedActionHandler(true);
      return false;
    }
    if (
      has(startupThirdStepForm.middleName) &&
      !startupThirdStepForm.middleName.length
    ) {
      stepThreeCardSelectedActionHandler(true);
      return false;
    }

    return 'disabled';
  };

That middle name thing is just something that is not required. The object could have around 15 keys maximum. So all I want to do with lodash -hopefully- is one more validation like this: (pseudo code)

    if (
       startupThirdStepForm has any key with an empty value
    ) {
      stepThreeCardSelectedActionHandler(false);
      return true;
    }

startupThirdStepForm is the object containing what I need to check. It is an empty object but the keys/values are created dynamically.

So I need to return true like in the pseudo code above, when there is something like this:

startupThirdStepForm: { key1: 'I have a value', key2: '' }

And return false when every key has a proper value, not an empty one.

If it's only about own properties you can use Object.values to get every property value as an array and then use .some to check if any of them are empty:

if (Object.values(startupThirdStepForm).some(v => v === '')) {

}

You can use _.some() to iterate the object's property, and check if a value is an empty string with _.isEqual() .

 const optional = ['middle'] const startupThirdStepForm = { key1: 'I have a value', key2: '', middle: '' } const result = _.some(_.omit(startupThirdStepForm, optional), _.partial(_.isEqual, '')) console.log(result) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script> 

And the same idea with lodash/fp:

 const fn = optional => _.flow( _.omit(optional), _.some(_.isEqual('')) ) const optional = ['middle'] const withoutOptional = fn(optional) console.log(withoutOptional({ key1: 'I have a value', key2: '' })) // true console.log(withoutOptional({ key1: 'I have a value', middle: '' })) // false 
 <script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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