Javascript嵌套对象深度搜索

时间:2016-06-17 18:11:45

标签: javascript

我想创建一个函数,它搜索嵌套对象中的现有键,并报告该值。

问题是,如果input ='d',我得到undefined,我希望'test-d'。 看起来我错过了一个没有找到的回报

我的代码



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




0 个答案:

没有答案
相关问题