How do I extract the values of an object?

1

I'm trying to make a simple login using information taken from a database in the form of json . I took that information using http.get and save it in a variable called this.info .
So what I want to do is the following:

  • Extract the values of an object within json (in this case this.info ) and save them in a variable.
  • Use that variable and compare it with a "linked" variable with information of a [(ngModel)] and if it is true that it shows a alert .
  • I've already tried using for , foreach , map . And at the time of making the comparison marks as false.

    Here is the code you used as mentioned above.
    map

    us: any;
    cn: any;'
    this.us = this.info.map(({ username }) => username);
    this.cn = this.info.map(({ contrasena }) => contrasena);
    

    for

    us = [];
    cn = [];
    for (let  x of this.info) {
      this.us.push(x.username);
      this.cn.push(x.password);
    }
    

    forEach

    this.info.forEach(function(x) {
        this.us.push(x.usuario);
        this.cn.push(x.contrasena);
    });
    

    But it goes wrong when doing the following:

    // this.usern y this.passw vienen del [(ngModel)]
    if (this.usern == this.us) {
        if(this.passw == this.cn) {
            alert('Datos Correctos');
        } 
    } else {
        alert('Datos Incorrectos');
    }
    
        
    asked by QuickAccount123 08.04.2018 в 03:35
    source

    1 answer

    3

    The problem is in the check, not in the map / for / forEach.

    If you analyze the first line, you are comparing a string, this.usern, with an array, this.us. I imagine that what you want to do is to check first is that the user is inside the array. You can do that with indexOf . indexOf returns the position within the array where the first occurrence is found. If you can not find it, return -1.

    let pos = this.us.indexOf(this.usern);
    if (pos > -1){
        // usuario existe
        if(this.passw == this.cn[pos]){
            alert("Correcto");
        }else{
            alert("Contraseña incorrecta");
        }
    }else{
        alert("Usuario no existe");
    }
    

    On the other hand, what you're doing, do not put it in a real app ever, since you do not have to send user passwords to the client, it would be very easily hacked. The passwords must always be on the server and hasheadas.

        
    answered by 08.04.2018 в 10:47