In development, we often need to check whether a key exists in an object or not. You may know one or two way to do it, but there are some other methods worth exploring. If you're interested in learning more, keep reading.
In this blog, I will demonstrate four different ways to perform this check. Each method has its pros and cons, so it's essential to understand all of them. This way, when the need arises, we can choose the most suitable approach.
Using in
operator.
In JavaScript in
operation used to check a property exist in an object or not. It return true
if exist else false
.
Note: It also includes properties that come from inheritance or prototype chaining. So, when you need to check purely for properties of the object itself, it may not return the desired result.
Complexity is O(1)
.
const user = {
fullName: "Shakil Ahmed",
age: 22,
isStudent: true,
};
// structure "keyName" in object
console.log("fullName" in user); // true
console.log("age" in user); // true
console.log("institute" in user); // false
Using hasOwnProperty
method.
hasOwnProperty
is an object method, it's purpose is same as in
operator. But different is it checks only object own property excluding inheritance or prototype chaining property. So it return pure result.
Put the key name in method argument and it will return true
if it contain key else false
.
Complexity is O(1)
, so performance is also good.
const user = {
fullName: "Shakil Ahmed",
age: 22,
isStudent: true,
};
console.log(user.hasOwnProperty("fullName")); // true
console.log(user.hasOwnProperty("age"));// true
console.log(user.hasOwnProperty("institute")); // false
Using optional chaining
Optional chaining is an ES11 feature that helps access values without throwing Uncaught TypeError
errors. When a key doesn't exist, it returns undefined
; otherwise, it returns the value. To convert the result into a boolean value, prepend !!
to the expression.
Complexity to check is O(1)
, so performance is good.
const user = {
fullName: "Shakil Ahmed",
age: 22,
isStudent: true,
};
console.log(user?.fullName); // Shakil Ahmed
console.log(!!user?.fullName); // true
console.log(user?.id); // undefined
console.log(!!user?.id); // false
However, it has a limitation: if the value is false
, 0
, undefined
, or null
any falsy value it will return false
, even if the key exists in the object.
const user = {
fullName: "Shakil Ahmed",
age: 22,
isStudent: false,
a: 0,
b: undefined,
c: null,
d: NaN,
};
console.log(user?.isStudent); // false
console.log(!!user?.isStudent); // false
console.log(user?.a); // 0
console.log(!!user?.a); // false
console.log(user?.b); // undefined
console.log(!!user?.b); // false
console.log(user?.c); // null
console.log(!!user?.c); // false
console.log(user?.d); // NaN
console.log(!!user?.d); // false
in the above examples, isStudent
, a
, b
, c
, d
variables exist in the object, but this technique returning false
only due to falsy values.
Comparing all keys
This process involves manually traversing over all keys of the object to check if a specific key exists.
Complexity: Traversing the entire object results in a time complexity of O(n)
, where n
is the number of keys in the object.
const user = {
fullName: "Shakil Ahmed",
age: 22,
isStudent: false,
a: 0,
b: undefined,
c: null,
d: NaN,
};
const isKeyExistInObject = (obj, key) => {
// here '!!' is to convert result in boolean you also can use Boolean() constructor.
return !!Object.keys(obj).find((eachKey) => eachKey === key);
};
In the above code, I've created a function to check the existence of a key. Here, I convert all keys of the object into an array using Object.keys(obj)
. Then, I traverse that array and check if it contains the specified key. If the key is found, find
returns that eachKey
; otherwise, it returns undefined
. Using !!
converts this result into a boolean. You can also use the Boolean(value)
constructor.
The isKeyExistInObject
function returns a boolean value.
console.log(isKeyExistInObject(user, "fullName")); // true
console.log(isKeyExistInObject(user, "first name")); // false
console.log(isKeyExistInObject(user, "age")); // true
console.log(isKeyExistInObject(user, "isStudent")); // true
console.log(isKeyExistInObject(user, "a")); // true
console.log(isKeyExistInObject(user, "b")); // true
console.log(isKeyExistInObject(user, "c")); // true
console.log(isKeyExistInObject(user, "d")); // true
console.log(isKeyExistInObject(user, "notExist")); // false
Note: Although this method is slightly more complex than other techniques, it works for any falsy values.
Example with nested objects
Here is a nested object and here we will use all of the above techniques
Example object:
const user = {
name: "Shakil",
age: 22,
studentData: {
id: "123",
bachelor: "CSE",
countryData: {
country: "Bangladesh",
capital: "Dhaka",
language: "Bangla",
},
},
};
Using in
:
// ========== is "name" exist
console.log("name" in user); // true
// ========== is "studentData" exist
console.log("studentData" in user); // true
// ========== is "id" exist
console.log(
"studentData" in user && "id" in user.studentData
); // true
// ========== is "language" exist
console.log(
"studentData" in user &&
"countryData" in user.studentData &&
"language" in user.studentData.countryData
); // true
Using hasOwnProperty
:
// ========== is "name" exist
console.log(user.hasOwnProperty("name")); // true
// ========== is "studentData" exist
console.log(user.hasOwnProperty("studentData")); // true
// ========== is "id" exist
console.log(
user.hasOwnProperty("studentData") &&
user.studentData.hasOwnProperty("id")
); // true
// ========== is "language" exist
console.log(
user.hasOwnProperty("studentData") &&
user.studentData.hasOwnProperty("countryData") &&
user.studentData.countryData.hasOwnProperty("language")
); // true
Using optional chaining
// ========== is "name" exist
console.log(!!user?.name); // true
// ========== is "studentData" exist
console.log(!!user?.studentData); // true
// ========== is "id" exist
console.log(
!!user?.studentData && !!user.studentData?.id
); // true
// ========== is "language" exist
console.log(
!!user?.studentData &&
!!user.studentData?.countryData &&
!!user.studentData.countryData?.language
); // true
Comparing all keys :
const isKeyExistInObject = (obj, key) => {
return !!Object.keys(obj).find(
(eachKey) => eachKey === key
);
};
// ========== is "name" exist
console.log(isKeyExistInObject(user, "name")); // true
// ========== is "studentData" exist
console.log(isKeyExistInObject(user, "studentData")); // true
// ========== is "id" exist
console.log(
isKeyExistInObject(user, "studentData") &&
isKeyExistInObject(user.studentData, "id")
); // true
// ========== is "language" exist
console.log(
isKeyExistInObject(user, "studentData") &&
isKeyExistInObject(user.studentData, "countryData") &&
isKeyExistInObject(user.studentData.countryData, "language")
); // true
In summary, knowing different ways to check for keys in JavaScript objects empowers developers to write more efficient and reliable code. Each method offers its own advantages, allowing flexibility in handling various scenarios. By familiarizing yourself with these techniques, you can enhance your JavaScript skills and tackle object-related challenges with ease. Keep exploring and experimenting to find the approach that best fits your needs. Happy coding!