LoDash _.has for multiple keys

YarGnawh picture YarGnawh · Mar 12, 2015 · Viewed 20.5k times · Source

Is there a method or a chain of methods to check if an array of keys exists in an object available in lodash, rather than using the following?

var params = {...}
var isCompleteForm = true;
var requiredKeys = ['firstname', 'lastname', 'email']

for (var i in requiredKeys) {
    if (_.has(params, requiredKeys[i]) == false) {
        isCompleteForm = false;
        break;
    }
}

if (isCompleteForm) {
    // do something fun
}

UPDATE

Thanks everyone for the awesome solutions! If you're interested, here's the jsPerf of the different solutions.

http://jsperf.com/check-array-of-keys-for-object

Answer

Allan Baptista picture Allan Baptista · Sep 9, 2015

I know the question is about lodash, but this can be done with vanilla JS, and it is much faster:

requiredKeys.every(function(k) { return k in params; })

and even cleaner in ES2015:

requiredKeys.every(k => k in params)