Categories
JavaScript Answers

How to check if a key exists in an object with Lodash and JavaScript?

Spread the love

Sometimes, we want to check if a key exists in an object with Lodash and JavaScript.

In this article, we’ll look at how to check if a key exists in an object with Lodash and JavaScript.

How to check if a key exists in an object with Lodash and JavaScript?

To check if a key exists in an object with Lodash and JavaScript, we can use the has method.

For instance, we write:

const obj = {
  foo: 1,
  bar: 2
}
console.log(_.has(obj, 'foo'))
console.log(_.has(obj, 'baz'))

We call has with the obj we want to check if the key exists in and the key we’re searching for.

Therefore, the first console log logs true and the 2nd one logs false.

Conclusion

To check if a key exists in an object with Lodash and JavaScript, we can use the has method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *