Bomber
Bomber

Reputation: 10957

check for empty property value using lodash

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...

Upvotes: 4

Views: 7973

Answers (5)

Hadi Abedi
Hadi Abedi

Reputation: 1

_.isEmpty(_.omitBy(obj, _.isEmpty))

This will return true if all obj properties values are set to ""

Upvotes: 0

One Mad Geek
One Mad Geek

Reputation: 529

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

Upvotes: 0

Amil Sajeev
Amil Sajeev

Reputation: 280

you can use isEmpty() from lodash like this

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

or


import isEmpty from 'lodash.isempty';

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

Upvotes: 1

Adam Boduch
Adam Boduch

Reputation: 11211

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

Upvotes: 5

Som Nath
Som Nath

Reputation: 36

_.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.

Upvotes: 1

Related Questions