Last active
April 20, 2024 08:35
-
-
Save MicroCBer/6d8a50d8bb433098a0718e7e073349ef to your computer and use it in GitHub Desktop.
find value in object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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