Reputation: 1990
I have an Object say obj
.I need to search for a property obj.property
if its not there(undefined
) search in obj.parent.property
.If its not there search in obj.parent.parent.property
and so on.. until I get that property
like this..
obj.property [undefined]
obj.parent.property [undefined]
obj.parent.parent.property [undefined]
obj.parent.parent.parent.property [found] .Terminate here.
Upvotes: 1
Views: 274
Reputation: 122027
You can use for...in
loop to crate recursive function that will search all nested objects for specified property and return its value.
var obj = {lorem: {ipsum: {a: {c: 2}, b: 1}}}
function getProp(obj, prop) {
for (var i in obj) {
if (i == prop) return obj[i]
if (typeof obj[i] == 'object') {
var match = getProp(obj[i], prop);
if (match) return match
}
}
}
console.log(getProp(obj, 'b'))
Upvotes: 2
Reputation: 386520
You could use a recursive approach by checking if the property exist, otherwise call iter
again with the parent key.
function iter(object) {
return 'property' in object ? object.property : iter(object.parent);
}
var object = { parent: { parent: { parent: { parent: { property: 42 } } } } };
console.log(iter(object));
Upvotes: 0
Reputation: 7433
You need to recrusively check for the properties at each level. Check this answer:
Iterate through object properties
Upvotes: 0