Introduction
In this lab, we will be exploring how to check if a target value exists in a JSON object using JavaScript. We will be using the hasKey() function which allows us to sequentially check the keys in the object to determine if the target value is present. This lab will provide a better understanding of how to work with JSON objects in JavaScript.
JavaScript Function to Check if Object Has Key
To check if a target value exists in a JavaScript object, use the hasKey function.
The function takes two arguments: obj, the JSON object to search in, and keys, an array of keys to check for. Here are the steps to check if the object has the given key(s):
- Check if the
keysarray is non-empty. If it is empty, returnfalse. - Use the
Array.prototype.every()method to iterate over thekeysarray and sequentially check each key to internal depth of theobj. - Use the
Object.prototype.hasOwnProperty()method to check ifobjdoes not have the current key or is not an object. If either of these conditions is true, stop propagation and returnfalse. - Otherwise, assign the key's value to
objto use on the next iteration. - If the
keysarray has been iterated over successfully, returntrue.
Here's the code for the hasKey function:
const hasKey = (obj, keys) => {
return (
keys.length > 0 &&
keys.every((key) => {
if (typeof obj !== "object" || !obj.hasOwnProperty(key)) return false;
obj = obj[key];
return true;
})
);
};
Here are some examples of how to use the hasKey function:
let obj = {
a: 1,
b: { c: 4 },
"b.d": 5
};
hasKey(obj, ["a"]); // true
hasKey(obj, ["b"]); // true
hasKey(obj, ["b", "c"]); // true
hasKey(obj, ["b.d"]); // true
hasKey(obj, ["d"]); // false
hasKey(obj, ["c"]); // false
hasKey(obj, ["b", "f"]); // false
Summary
Congratulations! You have completed the Check if Object Has Key lab. You can practice more labs in LabEx to improve your skills.