Skip to content Skip to sidebar Skip to footer

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.proper

Solution 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'))

Solution 2:

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));

Solution 3:

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

Iterate through object properties


Post a Comment for "Recursively Searching For A Property In Object"