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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With