Search code examples
javascriptlodash

Is there a one liner in JavaScript or Lodash for includes() with multiple values?


In my program I'm often validating objects. That validation often includes checking if an object has all defined keys. Is there a one liner (short way, preferably single function call) to check that using pure JavaScript or Lodash (which I'm also using)?

So far I do it like in the code below. I'm looking for a more concise way.

function validator(object) {
  let requiredKeys = ['key1', 'key2', 'key3'];
  for (let requiredKey of requiredKeys) {
    if (!object.hasOwnProperty(requiredKey)) {
      return false;
    }
  }
  return true;
}

validator({ key1: 1, key2: 2, key3: 3 });  // returns true
validator({ key1: 1, key2: 2 });           // returns false

NOTE 1: I can operate both on object or object.keys(), so the one-liner function can take Object as well as Array.

NOTE 2: There is includes() method on Array, but it takes only single argument. I'm looking for a version that would take multiple ones.


Solution

  • You could check with Array#every and thisArg for the object.

    function check(object) {
        return ['key1', 'key2', 'key3'].every({}.hasOwnProperty, object);
    }
    
    console.log(check({}));
    console.log(check({ key1: 1 }));
    console.log(check({ key1: 1, key2: 2 }));
    console.log(check({ key1: 1, key3: 3 }));
    console.log(check({ key1: 0, key2: 0, key3: 0 }));

    Without thisArg

    function check(object) {
        return ['key1', 'key2', 'key3'].every({}.hasOwnProperty.bind(object));
    }
    
    console.log(check({}));
    console.log(check({ key1: 1 }));
    console.log(check({ key1: 1, key2: 2 }));
    console.log(check({ key1: 1, key3: 3 }));
    console.log(check({ key1: 0, key2: 0, key3: 0 }));