How to filter an array and return the entire object - Angular

Moumita akter picture Moumita akter · Sep 12, 2018 · Viewed 34.9k times · Source
export class ResultComponent {
    students: AdmissionFormData[]

    constructor(private adStudent: AdmissionFormService) {
        adStudent.adFormGet().subscribe(
            x => this.students = x
        )
    }

    onSubmit(value) {

    }
}

In the students array, I have the data. And onSubmit is the function and value is the parameter "roll"

And the HTML File:

<div class="form">
<div class="col-md-5 offset-md-3">
  <div class="card">
      <div class="card-header text-center">
          <h3 id="form_name" >Search Result</h3>
      </div>

      <div class="card-block">
          <form (ngSubmit)="onSubmit(f.value)" #f="ngForm" >
              <div class="form-group">
                <label for="">Roll</label>
                <input
                type="number" 
                ngModel
                name="reg" 
                #reg="ngModel" 
                [min]="99999"
                placeholder="Ex: 224697"
                class="form-control">
                <p class="text-danger" *ngIf="!reg.valid && reg.touched">Roll Should have at least 6 letter</p>
              </div>
              <input 
              type="submit"
              value="Search" 
              class="btn btn-block btn-outline-success">
          </form>
      </div>
  </div>

The array

I want to search for the roll in this array and if I find a match then I would like to return the whole array and use it somewhere.

Now how can I do that?

I think I made a mistake before so I edit the question. Please forgive me I'm new here.

Answer

Sajeetharan picture Sajeetharan · Sep 12, 2018

You can use array.filter with the property you want to filter, since you have not mentioned the property, assuming it as fullname

this.students = this.students.filter(t=>t.fullname ===roll)[0];

or if you want single Object, use array.find

let studentObj =  this.students.find(t=>t.fullname ===roll);