0

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?

4 Answers 4

1

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

Demo

Sign up to request clarification or add additional context in comments.

1 Comment

Hi Sachila, that didn't work. I still get undefined.
0

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.

Comments

0

Your problem because forEach not return everything.

In typescript you can try this one.

getState(stateId) {
    return this.states.find(x => x.stateId == stateId);
}

Comments

0

From Docs
forEach() executes the callback function once for each array element; unlike map() or reduce() 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;
          }  
        });
      }

Live Demo;

Or you could use find() method

getState(stateId){
    return this.states.find(element=> {
      if(element.stateId == stateId){
        return element;
      }  
    });

Live Demo

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.

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.