[英]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.
该对象最多可以包含15个键。 So all I want to do with
lodash
-hopefully- is one more validation like this: (pseudo code) 因此,我想要对
lodash
-hopefully-做的就是这样的另一项验证:(伪代码)
if (
startupThirdStepForm has any key with an empty value
) {
stepThreeCardSelectedActionHandler(false);
return true;
}
startupThirdStepForm
is the object containing what I need to check. startupThirdStepForm
是包含我需要检查的对象。 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: 因此,当出现以下情况时,我需要像上面的伪代码一样返回
true
:
startupThirdStepForm: { key1: 'I have a value', key2: '' }
And return false
when every key has a proper value, not an empty one. 当每个键都有一个适当的值而不是一个空值时,返回
false
。
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: 如果仅关于自己的属性,则可以使用
Object.values
来获取每个属性值作为数组,然后使用.some
检查其中是否为空:
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()
. 您可以使用
_.some()
迭代对象的属性,并检查的值是一个空字符串_.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: 和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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.