Skip to content

Instantly share code, notes, and snippets.

@AnechaS
Last active April 25, 2023 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AnechaS/2a6d52b1ec8fc92facaec226a75fa090 to your computer and use it in GitHub Desktop.
Save AnechaS/2a6d52b1ec8fc92facaec226a75fa090 to your computer and use it in GitHub Desktop.
Javascript find property path in object with a value.
/**
* 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;
}
}
}
}
@AnechaS
Copy link
Author

AnechaS commented May 21, 2021

Example

const object = {  
  user: {      
    $inQuery: { 
      className: "UserDetail", 
      where: { firstname: "{{value}}" } 
    },    
  },  
};

findPropertyPathWithValue(object,  "{{value}}"); // => user.$inQuery.where.firstname

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment