我想创建一个函数,它搜索嵌套对象中的现有键,并报告该值。
问题是,如果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))