The with forEach function returns undefined even with the return statement

I just make a function to check the value of something in my array of objects, but for some reason it keeps returning undefined . Why is this?

Demo: http://jsfiddle.net/cNYwz/1/

 var data = [{ "Key": "1111-1111-1111", "Email": " test@test.com " }, { "Key": "2222-2222-2222", "Email": " test@boo.com " }]; function getByKey(key) { data.forEach(function (i, val) { if (data[val].Key === key) { return data[val].Key; } else { return "Couldn't find"; } }); } var asd = getByKey('1111-1111-1111'); console.log(asd); 
+4
source share
5 answers

In your function, you return from the function passed to forEach , not from getByKey .

You can adapt it like this:

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

But this will lead to the transition across all elements, even if the element is immediately found. This is why you should 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 a value, not a key. I suppose that was the intention. You may also have been confused with another iterative function: the first argument passed to the callback you pass forEach is an array element.

+10
source

Try saving the positive result as a variable, and then return that variable (or “Could not be found” if nothing is written) at the end of the function after the forEach loop.

 function getByKey(key) { var result; data.forEach(function (val, i) { if (data[val].Key === key) { result = data[val].Key; } }); return result || "Couldn't find"; } 
+1
source

Your getByKey function does not have a return statement. Two returns for the anonymous function used by forEach.

+1
source

You are not returning anything to external coverage, try this alternative:

 function getByKey(key) { var result = data.filter(function (i, val) { return data[val].Key == key; }); return result.length ? result : 'Not found'; } 
0
source

In addition to the ideas in the other answers, you'd better use Array.prototype.some rather than forEach. This will allow you to stop when you find the first match:

 function getByKey(key) { var found = null; data.some(function (val) { if (val.Key === key) { found = val; return true; //stop iterating } }); return found; } 

You can also use a filter that can return an array containing only those objects where the key is located:

 function filter_array_by_key(key){ return data.filter(function(v){ return v.Key===key; }; } 

To get the first matching object, you can use filter_array_by_key(key)[0] , which will give undefined if there was no match.

0
source

Source: https://habr.com/ru/post/1479301/


All Articles