Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LoDash _.has for multiple keys

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

like image 306
YarGnawh Avatar asked Mar 12 '15 04:03

YarGnawh


1 Answers

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) 
like image 60
Allan Baptista Avatar answered Oct 14 '22 06:10

Allan Baptista