You didn't put return
before this.traverse(data[i].children, pk);
.
EDIT:
var Tree = {
data: {
0: {
pk: 1,
},
1: {
pk: 2,
},
2: {
pk: 3,
children: {
0: {
pk: 11,
},
1: {
pk: 22,
},
2: {
pk: 33,
},
},
},
},
traverse: function(data, pk) {
for (var i in data) {
// console.log(data[i]);
if(data[i].pk && data[i].pk == pk)
return data[i];
if (typeof(data[i].children) == 'object') {
var retVal = this.traverse(data[i].children, pk);
if (typeof retVal!='undefined') {//here was the logical problem,there might be more than one
//object, we can't return the result of traversing first one.
//So we will check, if no return, we go on searching
return retVal;
}
}
};
},
};
alert(Tree.traverse(Tree.data, 1).pk);
alert(Tree.traverse(Tree.data, 22).pk);
check live here: http://jsfiddle.net/rq4LK/