I am looking for a solution to retrieve the value of a property from an object graph, and I am wondering if there is a more efficient alternative to the method I have outlined below.
Instead of using recursion, I have chosen tree traversal because it conserves stack frames and memory, and it is also faster.
For example:
const obj = {someObj:{}, someOtherObj: {nestedObjet: {featureRole: "canary"}}}
const prop = findProperties(obj, "featureRole");
console.log(prop); //canary
- Breadth First Search of Properties
findProperty(obj: Record<string, any>, propId: string): any {
if (obj && obj[propId] != undefined) {
return obj[propId];
}
const props = [obj];
while (props.length) {
const prop = props.shift();
if (typeof prop === 'object') {
if (prop && prop[propId] != undefined) {
return prop[propId];
}
for (const innerProp in prop) {
if (Object.prototype.hasOwnProperty.call(prop, innerProp) && typeof prop[innerProp] === 'object') {
props.push(prop[innerProp]);
}
}
}
}
}