Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash - check if object contains any of the key from the array

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
like image 896
Shota Avatar asked Feb 01 '17 13:02

Shota


1 Answers

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.

like image 200
alebianco Avatar answered Nov 15 '22 06:11

alebianco