skip to Main Content

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.

2

Answers


  1. Perhaps this?

    const hasMissing = obj => {
      const vals = Object.values(obj);
      return vals.filter(val => val !== null && val !== undefined).length !== vals.length
    };  
    const obj =  { "a":null, "b":"there", "c":0, "d":undefined }
    console.log(obj);
    
    console.log(JSON.stringify(obj)); // so we cannot use that
    
    console.log("Missing?",hasMissing(obj))
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search