lodash check object properties has values

Viewed 53250

I have object with several properties, says it's something like this

{ a: "", b: undefined }

in jsx is there any one line solution I can check whether that object's property is not empty or has value or not? If array there's a isEmpty method.

I tried this

const somethingKeyIsnotEmpty = Object.keys((props.something, key, val) => {
        return val[key] !== '' || val[key] !== undefined
})
5 Answers

You can use lodash _.every and check if _.values are _.isEmpty

const profile = {
  name: 'John',
  age: ''
};

const emptyProfile = _.values(profile).every(_.isEmpty);

console.log(emptyProfile); // returns false

A simple and elegant solution to check if all property values in an object is empty or not is following,

const ageList = {
  age1: 0,
  age: null
};

const allAgesEmpty = _.values(ageList).every((age) => !age);

console.log(allAgesEmpty); // returns true

Regarding the function inside _.every

  • Note: Do not use _.empty inside every as empty of a number always return false. Read more here: https://github.com/lodash/lodash/issues/496
  • Note: if a property has a boolean value then you may need to modify the function even more

const profile = { name: 'John', age: '' };

const emptyProfile = .values(profile).every(.isEmpty);

This solution is more efficient to check if each key is really empty

Related