Timo Jokinen Timo Jokinen - 3 months ago 7
Javascript Question

JavaScript For Loop does not return

My problem is that a loop that is called in another for loop and should return an object does not return anything. When I set a breakpoint to the return statement the object is there but undefined in my callback function. types object is a global object that contains many objects as properties with the properties "title" and "id".

function searchObj(obj, query) {
for (var key in obj) {
var value = obj[key];

if (typeof value === 'object') {
searchObj(value, query)
}

if (value === query) {
return obj;
}
}
}


The function is called from here:

function callback(data){
var logs = [];
var results = data.d.results;

for (var i = 0; results.length; i++) {
var item = results[i];

var action = util.searchObj(types, item.ActionId);

var obj = {
'Created': item.Created,
'Text': String.format(action.title, item.Author.Title),
'Author': item.Author
}
logs.push(obj);
}
console.log(logs);
}

Answer

Try this:

function searchObj(obj, query) {
    for (var key in obj) {
        var value = obj[key];

        if (typeof value === 'object') {
            var result = searchObj(value, query);
            if (result) {
                return result;
            }
        }

        if (value === query) {
            return obj;
        }
    }
}
Comments