1

I'm pulling a blank as to why this code isn't working as expected (jsFiddle here):

data = [
{
    "id": 1,
    "value": 4.56
}, 
{
    "id": 2,
    "value": 7.89
}];


function FindMe(searchID) 
{
    $.each(data, function (i, v) 
    { 
        // i=index, v=value (which is an object)
        if (v.id === searchID) 
        {
            console.log("Found: ");
            console.log(v);
            return v; // pass the desired object back to caller
        }
    });
}

console.clear();
var test = FindMe(2); // causes the console to show the correct object
console.log("Returned: ");
console.log(test); // shows "undefined" instead of a returned object

The function clearly does its job to find the correct array element (the console shows this as "Found"), but the return isn't happening. What's going wrong here?

4 Answers 4

4

That is because the looping function returns the found item, not the function FindMe.

Find me returns nothing.

function FindMe(searchID) {
 var result;    
    $.each(data, function (i, v) { // i=index, v=value (which is an object)
        if (v.id === searchID) {
            console.log("Found: ");
            console.log(v);
            result = v; // pass the desired object back to caller
            return false;
        }
    });
  return result;
}
Sign up to request clarification or add additional context in comments.

Comments

2

Your FindMe function has no return statement. You're just calling $.each...

Comments

0

jQuery.each just iterates, it does not collect. What you need is something similar to the native Array.prototype.filter like this one here:

function FindMe(searchID) {
    return data.filter(function(datum){
        return (datum.id === searchID);
    });
}

Most browsers should have Array.prototype.filter by now, except <= IE8.

Comments

0

you can use:

data = [{
"id": 1,
    "value": 4.56
}, {
    "id": 2,
        "value": 7.89
}];


function FindMe(searchID) {
     var searchObj=null;
    $.each(data, function (i, v) { // i=index, v=value (which is an object)
        if (v.id === searchID) {
            console.log("Found: ");
            console.log(v);
           searchObj = v; // pass the desired object back to   caller
            return false;
        }
    });
    return searchObj;
}

console.clear();
var test = FindMe(2); 
object
console.log("Returned: ");
console.log(test);
object

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.