Certainly! Below you'll find a TypeScript function that recursively searches an object for a specific value and returns the path to the property as a string. The path will be a dot-separated string indicating the nested levels of properties leading to the value. If the value is not found, the function returns null.
type Indexable = { [key: string]: any };
function findPropertyPath(obj: Indexable, valueToFind: any, currentPath: string = ''): string | null {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
const value = obj[key];
const newPath = currentPath ? `${currentPath}.${key}` : key;
// Check if the value matches the valueToFind considering the data type
if (value === valueToFind) {
return newPath;
} else if (typeof value === 'object' && value !== null) {
// If the property is an object, recurse into it
const result = findPropertyPath(value, valueToFind, newPath);
if (result !== null) {
// If the property is found in the nested object, return the path
return result;
}
}
}
}
// If the property is not found, return null
return null;
}
// Example usage:
const myObject = {
name: "Alice",
address: {
street: "123 Maple Street",
city: "Faketown",
postalCode: "12345"
},
hobbies: ["reading", "cycling", "hiking"]
};
const valuePath = findPropertyPath(myObject, "Faketown");
console.log(valuePath); // Output: "address.city"
This function iterates over each property of the given object. If the property's value is the one we're looking for, it returns the path. If the property is an object itself, the function is called recursively to search that object. The currentPath parameter is used to keep track of the property path during the recursion.
The function does not handle arrays or objects within arrays explicitly, but it will return the path to the array if the array itself is the value being searched for. If you need to handle arrays differently, you may need to modify the function to account for that.