Using the following code, the function returns several times. I need to break the recursion and return the result only once.
使用以下代码,该函数返回多次。我需要打破递归并只返回一次结果。
Any idea how to fix it?
知道怎么解决吗?
var data = {
item: [{
itemNested: [{
itemNested2: [{
id: "2"
}]
}]
}]
};
function findById (obj, id) {
var result;
for (var p in obj) {
if (obj.id) {
if(obj.id == id) {
result = obj;
break; // PROBLEM HERE dos not break
}
} else {
if (typeof obj[p] === 'object') {
findById(obj[p], id);
}
}
}
console.log(result);
return result;
}
var result = findById(data, "2");
alert(result);
1 个解决方案
#1
8
If the match is found, then you need to return the value. And in the parent call, if the recursive call returns a value, then it also has to return that value. You can modify your code like this
如果找到匹配项,则需要返回该值。在父调用中,如果递归调用返回一个值,那么它也必须返回该值。您可以像这样修改代码
function findById(obj, id) {
var result;
for (var p in obj) {
/*
if `id` is not in `obj`, then `obj.id` will evaluate to
be `undefined`, which will not be equal to the `id`.
*/
if (obj.id === id) {
return obj;
} else {
if (typeof obj[p] === 'object') {
result = findById(obj[p], id);
if (result) {
return result;
}
}
}
}
return result;
}
Now,
var result = findById(data, "2");
console.log(result);
will print
{ id: '2' }
#1
8
If the match is found, then you need to return the value. And in the parent call, if the recursive call returns a value, then it also has to return that value. You can modify your code like this
如果找到匹配项,则需要返回该值。在父调用中,如果递归调用返回一个值,那么它也必须返回该值。您可以像这样修改代码
function findById(obj, id) {
var result;
for (var p in obj) {
/*
if `id` is not in `obj`, then `obj.id` will evaluate to
be `undefined`, which will not be equal to the `id`.
*/
if (obj.id === id) {
return obj;
} else {
if (typeof obj[p] === 'object') {
result = findById(obj[p], id);
if (result) {
return result;
}
}
}
}
return result;
}
Now,
var result = findById(data, "2");
console.log(result);
will print
{ id: '2' }