Anonymous
Anonymous

Reputation: 1990

Recursively searching for a property in object

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

Answers (3)

Nenad Vracar
Nenad Vracar

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

Nina Scholz
Nina Scholz

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

ganders
ganders

Reputation: 7433

You need to recrusively check for the properties at each level. Check this answer:

Iterate through object properties

Upvotes: 0

Related Questions