0

Why can't I always get the value of d? I want to get the value of the specified node in a deeper object, which may be a string, a number, or a complex object.

var a = {
  a: 1,
  b: {
    c: {
      f: 3
    },
    d: 2
  }
}

function fun(foo, key) {
  for (var f in foo) {
    if (f == key) {
      return foo[f];
    } else {
      fun(foo[f], key)
    }
  }
}
console.log(fun(a, 'd'));
mplungjan
  • 169,008
  • 28
  • 173
  • 236
yakiler
  • 31
  • 6
  • It seems your algorithm is incorrect. Plus, you don't always return a result, so that's why you get `undefined` very often. – sjahan Jul 16 '18 at 13:34

2 Answers2

0

If the key exists in the object you are examining, return it directly. Else, browse each property to see if it contains it. As soon as you find a value, return it.

Be careful: if you have two nested properties with the same key, it will only get you the first. Auto-discovery is not magical.

var a = {
  a: 1,
  b: {
    c: {
      f: 3
    },
    d: 2
  }
}

function fun(obj, key) {
  if(obj[key]) return obj[key];
  for (var prop in obj) {
      var result = fun(obj[prop], key);
      if(result) return result;
  }
}
console.log(fun(a, 'd'));
sjahan
  • 5,720
  • 3
  • 19
  • 42
0

The problem lies in your algorithm. It returns the correct value when the key matches but the function stack is not propagating that value to the console.log function.

Try updating the function in such a way that it propagates the value properly. An example is as follow:

var a = { a: 1, b: { c: { f: 3 }, d: 2 } }
function fun(foo, key) {
  let x = undefined;
  for (var f in foo) {
    if (f == key) {
      x = foo[f];
    } else {
      x = fun(foo[f], key)
    }
  }
  return x;
}
console.log(fun(a, 'd'));
Aayush Sharma
  • 779
  • 4
  • 20
  • Thank you very much, this modification of debugging is normal to complete each branch condition, it seems that I am still not familiar with the idea of recursion – yakiler Jul 16 '18 at 13:48