So I have an object and array. I want to check whether the object contains any of the keys from the array. Something like this:
Object:
const user = {
firstname: 'bob',
lastname: 'boblastname'
email: '[email protected]'
}
Arrays:
const lastname = ['lastname'];
const userDetails = ['firstname', 'email'];
So when checking for key existence it should return true. Example:
_.includesKey(user, lastname) // true
_.includesKey(user, userDetails ) // true
I know the question asks about lodash, but I always wonder why would you use a third party library to perform a rather trivial task
A way to approach the problem with the basic js tools could be
const user = {
firstname: 'bob',
lastname: 'boblastname',
email: '[email protected]'
}
const lastname = ['lastname'];
const userDetails = ['firstname', 'email'];
const hasLastName = lastname.every(prop => prop in user)
const hasDetails = userDetails.every(prop => prop in user)
console.log("has last name?", hasLastName)
console.log("has user details?", hasDetails)
it makes your project smaller by not bloating it with external libraries, it's most certainly faster and i'd argue it's even easier to read and understand.
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