Reputation: 7378
I have the following code to go through a list of objs and find the obj with the "Title" field equal to objTitle
function objFinder(objTitle, event, objs) {
can.each(objs, function(obj, key) {
if (obj["Title"].trim() == objTitle.trim()) {
console.log(obj)
console.log(objTitle + " found")
return obj;
}
})
}
I have gone through in the debugger in chrome and seen that it does hit the return statement and the obj in the return statement is the correct one. The problem is when I do console.log of this function it shows as undefined and when I evaluate the statement in console it returns undefined. Why is this?
can.each() is just a package implementation of a foreach loop
Upvotes: 0
Views: 46
Reputation: 809
As Vlad states, your return just jumps out of the anonymous function given to each().
To solve this, you could do something like this:
function objFinder(objTitle, event, objs) {
//Btw. where do you define "can"?
var retObj = undefined;
can.each(objs, function(obj, key) {
if (obj["Title"].trim() == objTitle.trim()) {
console.log(obj)
console.log(objTitle + " found")
retObj = obj;
return;
}
});
return retObj;
}
Cheers,
Florian
Upvotes: 0
Reputation: 2565
Have the callback return false when you find the right object:
function objFinder(objTitle, event, objs) {
var result = null;
can.each(objs, function(obj, key) {
if (obj["Title"].trim() == objTitle.trim()) {
console.log(obj)
console.log(objTitle + " found")
result = obj;
return false;
}
})
return result;
}
Upvotes: 2
Reputation: 179046
The return
statement is for its function
parent, which is not objFinder
.
function objFinder(objTitle, event, objs) {
can.each(objs, function(obj, key) {
// ^^^^^^^^
if (obj["Title"].trim() == objTitle.trim()) {
console.log(obj)
console.log(objTitle + " found")
return obj;
// ^^^^^^
}
});
}
Upvotes: 1