Reputation: 1841
I have an object array that contains states. It has three fields (id, name, abbr)
To simplify things, I'll use three states:
states: any = [{
"stateId": 3,
"stateName": "Arizona",
"stateAbbreviation": "AZ"
},
{
"stateId": 4,
"stateName": "Arkansas",
"stateAbbreviation": "AR"
},
{
"stateId": 5,
"stateName": "California",
"stateAbbreviation": "CA"
}]
I have a provider where I want to return an object if it matches the stateId I pass it.
So in my provider I have the following funciton:
getState(stateId){
this.states.forEach(function(element) {
if(element.stateId == stateId){
return element;
}
});
}
In my home controller I simply call it like this:
console.log('State is: ', this.states.getState(50));
But I'm getting the error: undefined.
What am I doing wrong?
Upvotes: 0
Views: 161
Reputation: 12036
From Docs
forEach()
executes the callback function once for each array element; unlikemap()
orreduce()
it always returns the value undefined and is not chainable
You need filter() method
Modified Code
getState(stateId){
return this.states.filter(element=> {
if(element.stateId == stateId){
return element;
}
});
}
Or you could use find() method
getState(stateId){
return this.states.find(element=> {
if(element.stateId == stateId){
return element;
}
});
filter()
runs till the end of the array, and invokes its callback on every item; in contrast to find()
which stops after having found one.
Upvotes: 0
Reputation: 297
Your problem because forEach
not return everything.
In typescript
you can try this one.
getState(stateId) {
return this.states.find(x => x.stateId == stateId);
}
Upvotes: 0
Reputation: 41445
Need to return the result of. So add a return statement. Also use the fitler
operator instead forEach
getState(stateId){
return this.states.filter(function(element) {
if(element.stateId == stateId){
return element;
}
});
}
Upvotes: 1
Reputation: 5886
Alternatively, you could use the filter
function:
getState(stateId){
return this.states.filter(function(element) {
return element.stateId == stateId);
});
}
Note the first return
statement used to return the result of the filter
function.
Upvotes: 0