I wrote these two functions in January 2023 because I kept mistyping paths into deeply nested API responses (an array index where an object key belonged), and I wanted the code to find the value, or the full path to it, for me. They're still valid JavaScript.
Finding the Value of a Specific Key in a JSON Object
The first solution is to use a function that takes a JSON object and a key name as arguments, and returns the value of that key. The function uses recursion to search for the key in the JSON object, and if the key is found, it returns the value associated with it.
Here's an example of such a function in JavaScript:
function findKeyValue(obj, key) {
for (let prop in obj) {
if (prop === key) {
return obj[prop];
} else if (typeof obj[prop] === "object") {
let value = findKeyValue(obj[prop], key);
if (value !== undefined) {
return value;
}
}
}
}
You can use this function as follows:
const jsonObj = {"a": {"b": {"c": "value"}}}
console.log(findKeyValue(jsonObj, "c"))
This will return "value".
Find a Specific Key in a JSON Object
The second solution is to find the path of the key in the JSON object. This is useful if you need to access the key from within another part of your application.
Here's an example of a JavaScript function that finds the path of a key in a JSON object:
function findKeyPath(obj, key, path = "") {
if (Array.isArray(obj)) {
for (let i = 0; i < obj.length; i++) {
let subpath = findKeyPath(obj[i], key, path + "[" + i + "]");
if (subpath !== "") return subpath;
}
} else {
for (let prop in obj) {
if (prop === key) {
return path + (path ? "." : "") + prop;
} else if (typeof obj[prop] === "object") {
let subpath = findKeyPath(obj[prop], key, path + (path ? "." : "") + prop);
if (subpath !== "") return subpath;
}
}
}
return "";
}
With this function, you can find the path of a specific key in a JSON object, and use it to access the key from elsewhere in your application.
In conclusion, these two solutions are useful for different purposes when working with JSON objects in web development. By using either the findKeyValue or findKeyPath function, you can easily access the value of specific keys in your JSON objects.
For your technical person
Both functions are depth-first and return on the first match, so if a key appears more than once in the object, only the first one encountered comes back. Neither guards against circular references: a circular object will recurse until the call stack overflows.
