Skip to content

Instantly share code, notes, and snippets.

@MicroCBer
Last active April 20, 2024 08:35
Show Gist options
  • Save MicroCBer/6d8a50d8bb433098a0718e7e073349ef to your computer and use it in GitHub Desktop.
Save MicroCBer/6d8a50d8bb433098a0718e7e073349ef to your computer and use it in GitHub Desktop.
find value in object
function findPaths(obj, kwd, maxDepth = 1, exclude=[]) {
const paths = [];
function exploreObject(obj, path, depth) {
if (depth > maxDepth) {
return;
}
for (const key in obj) {
const value = obj[key];
const newPath = path ? `${path}.${key}` : key.toString();
if(exclude.some(v=>newPath.toLowerCase().includes(v.toLowerCase()))) continue;
if (value && typeof value === 'object') {
exploreObject(value, newPath, depth + 1);
} else if (value && value.toString()?.toLowerCase && value.toString()?.toLowerCase()?.includes(kwd.toLowerCase()) || newPath.toLowerCase().includes(kwd.toLowerCase())) {
paths.push(newPath);
}
}
}
exploreObject(obj, '', 0);
return paths;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment