0

I want to create a function, which search for an existing key in a nested object, and reports the value.

The problem is, if input ='d', I get undefined and I expect 'test-d'. It looks like I miss a return when it's not found

My code

var foo = {
  a: 'test-a',
  b: {
    myProp: 'test-prop',
    foo: {
      last: 'test-last'
    }
  },
  c: {
    d: 'test-d'
  }
};


var search = function(input, objs) {
  for (key in objs) {
    //   console.log(key+ '---'+ input);
    if (typeof objs[key] == 'object') {
      return search(input, objs[key]);
    } else {
      if (input == key) {
        return result = objs[input];
      }
    }
  }
}
console.log(search("d",foo))
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Yichz
  • 9,250
  • 10
  • 54
  • 92
  • Looks like you are returning early, problem in the `if(typeof objs[key] =='object'){ return search(input, objs[key]); }`, it does not get to c at all – Neil DCruz Jun 17 '16 at 18:16
  • Undefined, because your function never go to object 'c'. It's ending on foo['last'] – Darex1991 Jun 17 '16 at 18:18
  • oh, got it, I switch it to `var result = search(input, objs[key]); if(result){ return result; }else{ continue; }` and it worked. – Yichz Jun 17 '16 at 18:20

0 Answers0