Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

199
Views
Cómo usar "indexOf" en javascript

Hola, estoy usando Angular y estoy luchando por un problema. Me gustaría saber cómo usar el método "indexOf ()" en una matriz que tiene dos o más campos. Aquí está mi código:

Mi matriz:

 [ { "id":1, "name": "stuff", "surname": "stuff" }, { "id":2, "name": "stuff", "surname": "stuff" }, { "id":3, "name": "stuff", "surname": "stuff" } ]

en mi código angular, me gustaría que un usuario escriba una determinada identificación de la plantilla (en el formulario) y verifique si el usuario correspondiente existe en mi matriz. mi código angular es:

 <form #formValue="ngForm" (ngSubmit)="onClick(formValue)"> <div class="form-group"> <label for="exampleInputEmail1">Identifiant du challenge</label> <input type="text" name="_id" #_id="ngModel" [(ngModel)]="this.user._id" class="form-control" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[az]{2,4}$" placeholder="identifiant"> </div> <input type="submit" value="Submit" class="btn btn-primary"/> </form>

en mi archivo *.ts tengo un método que realizo en el evento de envío llamado "onClick" mire mi archivo ts:

 onClick(form: NgForm){ this.getUsers(form.value._id) } // get users method getUsers(id: String){ return this._http.get<any[]>(this.url + 'getAllChallenge').subscribe( (users)=>{ this.users=users; this.checkExist= this.users.indexOf(id) if(this.checkExist==-1){ alert("this id you typed doesn't exist in our array") } else{ /* here is my issue. this alert if is always printed enven If I type 1,2 or 3(an existing id)*/ alert("this Id exist") } } ); }

¡Gracias de antemano!

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Básicamente, no lo haces.

La función que desea utilizar es find() .

Le das una función que debería devolver verdadero o falso según lo que quieras. Luego devolverá el primer elemento que coincida, o undefined si ningún elemento lo hace. Entonces, si obtienes una coincidencia, existe, de lo contrario, no existe. No tiene que convertir explícitamente a un valor booleano, pero puede hacerlo.

 this.checkExist = Boolean(this.users.find(user => user.id === id));

Este también es un método findIndex() que devuelve el índice en lugar del objeto en sí mismo si lo prefiere, pero si lo está usando como un booleano, usar find() será más seguro (ya que no tendrá que verifique !== -1 ).

about 4 years ago · Juan Pablo Isaza Report

0

Si pasó el objeto a la función getUsers(), podría hacerlo. No sé si es posible en Angular.

 a={} b={} c=[a,b] c.indexOf(b) // = 1

De lo contrario, use el método find() como lo sugieren otros.

about 4 years ago · Juan Pablo Isaza Report

0

Deberías usar findIndex()

 var arr = [ { "id":1, "name": "stuff", "surname": "stuff" }, { "id":2, "name": "stuff", "surname": "stuff" }, { "id":3, "name": "stuff", "surname": "stuff" } ] let index = arr.findIndex((obj) => { return obj.id == 2 }) console.log(index)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!