Search code examples
javascriptlodash

How to check if every properties in an object are null


I have an object, sometimes it is empty like so {} other times it will have properties that are set to null.

{
  property1: null,
  property2: null
}

How can I determine if ALL the properties within this object is null? If they are all null then return false.

At the moment I'm using lodash to check for the first case where the object is simply {} empty. But I also need to cover the second case.

if (isEmpty(this.report.device)) {
  return false;
}
return true;

Solution

  • You can use Object.values to convert the object into array and use every to check each element. Use ! to negate the value.

    let report = {
      property1: null,
      property2: null,
    }
    
    let result = !Object.values(report).every(o => o === null);
    
    console.log(result);

    An example some elements are not null

    let report = {
      property1: null,
      property2: 1,
    }
    
    let result = !Object.values(report).every(o => o === null);
    
    console.log(result);

    Doc: Object.values(), every()