How do I check if a particular key exists in a JavaScript object or array?
If a key doesn't exist, and I try to access it, will it return false? Or throw an error?
How do I check if a particular key exists in a JavaScript object or array?
If a key doesn't exist, and I try to access it, will it return false? Or throw an error?
We can use -
hasOwnProperty.call(obj, key);
The underscore.js way -
This is an old question but I guess never to late to give an answer.
Imagine that you have an object "products" and two items. If you want to see if id already exists in this object you can use find()
log:
New awesome solution with JavaScript Destructuring:
Do check other use of JavaScript Destructuring
Here's a helper function I find quite useful
This
keyExists(key, search)
can be used to easily lookup a key within objects or arrays!Just pass it the key you want to find, and search obj (the object or array) you want to find it in.
How to use it:
Searching for keys in Arrays
Searching for keys in Objects
It's been pretty reliable and works well cross-browser.
vanila js
If you want to check if the object has at least one property in es2015
The accepted answer refers to Object. Beware using the
in
operator on Array to find data instead of keys:To test existing elements in an Array: Best way to find if an item is in a JavaScript array?