Can you write a Node.js function in TypeScript that searches an object for a specific property value, then returns the property name of the index? Please take into consideration data type values while building out this function e.g. a property with another nested property that must be searched.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Sure! Here's a sample Node.js function in TypeScript that does what you're asking:
typescript
function findPropertyNameByValue<T extends Record<string, any>>(obj: T, value: any): string | undefined {
function isValue(value: unknown): value is any {
return typeof value === 'number' || typeof value === 'string' || value === null;
}
function search(obj: T, value: any): string | undefined {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
if (isValue(obj[key]) && obj[key] === value) {
return key;
}
if (typeof obj[key] === 'object' && obj[key] !== null) {
const result = search(obj[key], value);
if (result !== undefined) {
return result;
}
}
}
}
return undefined;
}
return search(obj, value);
}
This function takes two arguments: an object and a value. It recursively searches the object and its nested properties for the value specified. If it finds the value, it returns the property name of the index where it was found. If it doesn't find the value, it returns undefined.
The isValue function checks if the given value is a primitive type (number, string, or null). This is used to ensure that only primitive types are compared for equality when searching the object.
The search function is a helper function that does the actual searching. It first checks if the value is a primitive type. If it is, it returns the property name if it matches the value. If it's not a primitive type, it checks if the value is an object. If it is, it calls the search function recursively on the object, passing in the value to search for. If a property name is found, it returns that. If not, it returns undefined.
Finally, the findPropertyNameByValue function calls the search function with the given object and value, and returns the result.