Geek Stocks
Geek Stocks

Reputation: 2030

Can Javascript and/or jQuery return objects this way?

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?

Upvotes: 1

Views: 45

Answers (4)

Maneesh Singh
Maneesh Singh

Reputation: 575

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

Upvotes: 0

Joseph
Joseph

Reputation: 119847

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.

Upvotes: 0

Mārtiņš Briedis
Mārtiņš Briedis

Reputation: 17762

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;
}

Upvotes: 4

Assaf Lavie
Assaf Lavie

Reputation: 75983

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

Upvotes: 2

Related Questions