Last active
April 25, 2023 15:01
-
-
Save AnechaS/2a6d52b1ec8fc92facaec226a75fa090 to your computer and use it in GitHub Desktop.
Javascript find property path in object with a value.
This file contains hidden or 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
/** | |
* Find property path in the object with a value | |
* @param {object} obj | |
* @param {any} value | |
* @return {string} | |
*/ | |
function findPropertyPathWithValue(obj, value) { | |
for (const key in obj) { | |
if (JSON.stringify(value) === JSON.stringify(obj[key])) { | |
return key; | |
} else if (typeof obj[key] === 'object') { | |
const pathname = findPropertyPathWithValue(obj[key], value); | |
if (pathname) { | |
return key + '.' + pathname; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example