Isaac
asked on
undefined returned from function
I don't understand why I get undefined below.
https://jsfiddle.net/isogunro/681j6nk6/1/
var index = -1;
var proj = "893x-3owe34p";
alert(getIndex(proj));
function getIndex(val){
var filteredObj = jsonFile.Result.Contracts.find(function(item, i) {
//console.log(item.Plan.Identification.PlanNumber)
if (item.Plan.Identification.PlanNumber == val) {
index = i;
return index;
}
//return index;
});
}
https://jsfiddle.net/isogunro/681j6nk6/1/
no such project "893x-3owe34p"
ASKER
Yes there is. "PlanNumber"
The last one in the Contracts array
The last one in the Contracts array
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
or maybe you want to do this
https://jsfiddle.net/HainKurt/rbuzLto5/
it sets index + returns found object...
var index = -1;
var proj = "893x-3owe34p";
var item = getIndex(proj)
alert(index);
alert(item);
function getIndex(val) {
var filteredObj = jsonFile.Result.Contracts.find(function(item, i) {
console.log(item.Plan.Identification.PlanNumber)
if (item.Plan.Identification.PlanNumber == val) {
index = i;
return item;
}
});
return filteredObj;
}
https://jsfiddle.net/HainKurt/rbuzLto5/
it sets index + returns found object...
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
What I should get back is 5.
If it's a function, how come it can't return the index? Just curious
If it's a function, how come it can't return the index? Just curious
Or like this - a bit more concise
var proj = "893x-3owe34p";
var filteredObj = jsonFile.Result.Contracts.find(function(item, i) {
return item.Plan.Identification.PlanNumber == proj
});
if (filteredObj) {
index = jsonFile.Result.Contracts.indexOf(filteredObj);
console.log(index);
}
You can - but you weren't
Your return was inside the find() function block not the getIndex() function block.
find() expects a true / false return based on whether the item was found or not - but this would end up with setting filteredObj to the found item - but you don't do anything with filteredObj and nothing is returned - hence the undefined.
Your return was inside the find() function block not the getIndex() function block.
find() expects a true / false return based on whether the item was found or not - but this would end up with setting filteredObj to the found item - but you don't do anything with filteredObj and nothing is returned - hence the undefined.
ASKER
Thanks Guys!
ASKER
Open in new window