简体   繁体   中英

Javascript Looping through JSON an array of object s

so i have a login form , and i want to check whether the entered name and password already exists in the JSON object , it will prompt a different message for both cases but thr problem is it's not doing it right , here's the code for more clarity :

     function registerInfo(){
     var name = document.forms[0].username.value;
     var pw = document.forms[0].pw.value

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var response = JSON.parse(xhttp.responseText);
        console.log(response);

    if (name === "" || pw === "") {
    alert ('please complete all the forms')
    } 

    for (var i = 0; i < response.loginfo.length; i++){
      if ( name === response.loginfo[i].username && pw === 
            response.loginfo[i].password) {
        alert('Welcome back ' + name);
        break;
        } // if statement curly braces
    } // loop curcly braces 

    for (var i = 0; i < response.loginfo.length; i++){
        if ( name != response.loginfo[i].username && pw != response.loginfo[i].pw){
        alert('Welcome here new ');
        break;
        } // if statement curcly braces 
        } // for 
      } // ready state if statement curly braces
    } // function curly braces
    xhttp.open("GET", "login.json", true);
    xhttp.send();

    return false;
   }

and here's the JSON Object for a quick test

     {
      "loginfo" : [
      { 
          "username" : "moh",
          "password" : "lol"
      },
      {
          "username" : "zaki",
          "password" : "123"
      }         
      ]
      }

the problem is when the user enters the username and the password which exists in the JSON object id does alert "Welcome back!" , but also the "welcome here new" , which i don't want to , since the latest alert is for new user which their credentials doesn't exist in the JSON object.

Simplest fix would be not allows second for-loop to be executed, if a match is found, so

  • Either set a flag if match is found and don't execute second for-loop if that flag is set.

  • Return instead of break from first for-loop.

But, you can make your code less verbose by using Array.prototype.some to check if any value matches

var hasMatch = response.loginfo.some( s => s.username === name && s.password === pw );

hasMatch returns true if the match is found

alert( "Welcome " + (hasMatch ? "back" + name : "here new" ) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM