简体   繁体   中英

Using Lodash, how can I check to see if an object's keys match an array of strings

Let's say I have an array of strings

const acceptableColors = ['PURPLE', 'BLUE', 'RED', 'GREEN']

and I have an object

const primaryColors = {
  RED: 'RED',
  BLUE: 'BLUE',
  GREEN: 'GREEN',
}

Using Lodash, what are some of the cleanest ways I can check to see that all of the values (or keys) in the primaryColors object are present in the acceptableColors array?

Currently I think I'm close with the below function, but it still needs tweaking.

const containsAllColors = (primaryColors, acceptableColors) => {
   if (_.has(acceptableColors, _.every(_.values(primaryColors)))) {
   console.log('true')
   }
   console.log('false')
}

You can get all keys of an object by _.keys(object) and all values by _.values(object) .

So, a cleaner (and more efficient) way in my opinion is to check if all keys are included in the acceptableColors and all values are also included in it.

There's a simple way to check if an array is a subset of another array with lodash:

_.difference(a, b).length === 0

I'll leave the rest to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM