Search code examples
javascriptobjectpropertieslodash

Is there a Javascript/Lodash function to check if an object is missing ANY properties?


I want to check a javascript object to see if any of it's properties are missing without checking each property individually.

I can use "hasownproperty" or do if/else statements to check if each one is null/undefined, I wanted a shorter way of checking an object.


Solution

  • Use Array::some() on object values (get them with Object.values()) (this will return true if ANY property's value is null or undefined):

    const obj =  { a: null, b: 'there', c: 0, d: undefined };
    
    console.log("Missing?", Object.values(obj).some(v => v === undefined || v === null));

    If you want it the fastest possible, write your own function:

    const obj =  { a: null, b: 'there', c: 0, d: undefined };
    
    function hasNullProperties(obj){
      for(const k in obj){
        if(obj[k] === undefined || obj[k] === null){
          return true;
        }
      }
      return false;
    }
    
    console.log("Missing?", hasNullProperties(obj));

    And a benchmark:

    enter image description here

    <script benchmark data-count="10000000">
    
    const obj =  { a: null, b: 'there', c: 0, d: undefined };
    
    // @benchmark Array::some()
    
    Object.values(obj).some(v => v === undefined || v === null);
    
    // @benchmark custom func
    function hasNullProperties(obj){
      for(const k in obj){
        if(obj[k] === undefined || obj[k] === null){
          return true;
        }
      }
      return false;
    }
    
    // @run
    hasNullProperties(obj);
    
    </script>
    <script src="https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js"></script>