check for empty property value using lodash

百般思念 提交于 2020-05-15 04:55:08

问题


I am trying to check the following for empty values using lodash:

data.payload{
      name: ""
}

My code:

import isEmpty from 'lodash.isempty';

if (isEmpty(data.payload)) {

The above is false, how can I validate for empty values?

I have this code in my helper:

export const isEmpty = some(obj, function(value) {
  return value === '';
}

);

In my action I have

    if (isEmpty(data.payload)) {

I get an error, ReferenceError: obj is not defined but I am passing the object...


回答1:


If you want to use isEmpty() to check for objects with nothing but falsey values, you can compose a function that uses values() and compact() to build an array of values from the object:

const isEmptyObject = _.flow(_.values, _.compact, _.isEmpty);

isEmptyObject({});
// -> true

isEmptyObject({ name: '' });
// -> true

isEmptyObject({ name: 0 });
// -> true

isEmptyObject({ name: '...' });
// -> false



回答2:


_.some(obj, function (value) { return value === "" })

You can use this, it will return true if there is any empty property and false if all are defined.




回答3:


you can use isEmpty() from lodash like this

if(_.isEmpty(data.payload.name)){
}

or


import isEmpty from 'lodash.isempty';

if (isEmpty(data.payload.name)) {
}



回答4:


You can use some or every from lodash to check generically all key has passed condition or some has passed condition.

["barney", 36, "test"].some(_.isEmpty); // false
["barney", 36, ""].some(_.isEmpty); // true

or

["barney", 36, "test"].every(_.isEmpty); // false
["", [], ""].every(_.isEmpty); // true


来源:https://stackoverflow.com/questions/45608332/check-for-empty-property-value-using-lodash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!