1

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.
Hemant
  • 1,938
  • 2
  • 16
  • 26

3 Answers3

1

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'))
Nenad Vracar
  • 111,264
  • 15
  • 131
  • 153
0

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));
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358
0

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

Iterate through object properties

Community
  • 1
  • 1
ganders
  • 7,130
  • 16
  • 64
  • 112