Sometimes, we want to find by key deep in a nested array with JavaScript.
In this article, we’ll look at how to find by key deep in a nested array with JavaScript.
How to find by key deep in a nested array with JavaScript?
To find by key deep in a nested array with JavaScript, we can recursively search each level of the nested array.
For instance, we write
const deepSearchByKey = (object, originalKey, matches = []) => {
if (object !== null) {
if (Array.isArray(object)) {
for (const arrayItem of object) {
deepSearchByKey(arrayItem, originalKey, matches);
}
} else if (typeof object === "object") {
for (const key of Object.keys(object)) {
if (key === originalKey) {
matches.push(object);
} else {
deepSearchByKey(object[key], originalKey, matches);
}
}
}
}
return matches;
};
to define the deepSearchByKey function.
In it, we check if object isn’t null.
If it is, then we check if object is an array with Array.isArray.
If it is, then we call deepSearchByKey to search for the key we’re looking for.
Otherwise, if object is an object, which we check with typeof object === "object", then we loop through the keys of the object that we get from Object.keys.
If key equals originalKey then we push the object to matches.
Otherwise, we call deepSearchByKey to search the object[key] object.
Conclusion
To find by key deep in a nested array with JavaScript, we can recursively search each level of the nested array.