Skip to content Skip to sidebar Skip to footer

Lodash Check Object Properties Has Values

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 no

Solution 1:

In lodash, you can use _.some

_.some(props.something, _.isEmpty)

Solution 2:

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

Solution 3:

Possible ways:

Iterate all the keys and check the value:

let obj = {a:0, b:2, c: undefined};

let isEmpty = false;

Object.keys(obj).forEach(key => {
    if(obj[key] == undefined)
        isEmpty = true;
})

console.log('isEmpty: ', isEmpty);

Use Array.prototype.some(), like this:

let obj = {a:0, b:1, c: undefined};

let isEmpty = Object.values(obj).some(el => el == undefined);

console.log('isEmpty: ', isEmpty);

Check the index of undefined and null:

let obj = {a:1, b:2, c: undefined};

let isEmpty = Object.values(obj).indexOf(undefined) >= 0;

console.log('isEmpty: ', isEmpty);

Solution 4:

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

Post a Comment for "Lodash Check Object Properties Has Values"