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!
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 ).
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) // = 1De lo contrario, use el método find() como lo sugieren otros.
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)