Function with forEach returns undefined even with return statement

In your function, you’re returning from the function passed to forEach, not from getByKey.

You could adapt it like this :

function getByKey(key) {    
    var found = null;
    data.forEach(function (val) {
        if (val.Key === key) {
            found = val;
        }
    });
    return found;
}

But this would iterate over all elements, even if the item is immediately found. That’s why you’d better use a simple for loop :

function getByKey(key) {    
    for (var i=0; i<data.length; i++) {
         if (data[i].Key === key) {
            return data[i];
        }
    }
}

Note that I also adapted your code to return the value, not the key. I suppose that was the intent. You might also have been confused with another iteration function : the first argument passed to the callback you give to forEach is the element of the array.

Leave a Comment