简体   繁体   中英

Javascript - Alert first item in object's arrays?

I get an API server response back with the errors section looking like this:

"errors": {
    "username": [
        "The username field is required."
    ],
    "password": [
        "The password field is required.",
        "The password is too short."
    ]
}

To display a single error, I'd do this: alert(results.body.errors.username); manually.

What I need to do is to map over the errors object if it exists and alert only the very first item's error.

So based on the above API response, first alert should be The username field is required.

Once corrected by the user, providing the user didn't touch the password field yet and they resubmit, they'll get another API response with errors, so the next alert error should be The password field is required.

Finally, once they put a single character and resubmit, the next alert should be The password is too short.

After that no more alerts, since there are no more errors to display.

Any idea how to get this to work?

considering this is the response:

var response = {
  "errors": {
    "username": [
      "The username field is required."
    ],
    "password": [
      "The password field is required.",
      "The password is too short."
    ]
  }
}

this will do the trick

alert(response.errors[Object.keys(response.errors)[0]][0])

in your case replace response with results.body

Demo 1: The username field is required.

 var response = { "errors": { "username": [ "The username field is required." ], "password": [ "The password field is required.", "The password is too short." ] } } alert(response.errors[Object.keys(response.errors)[0]][0]); 

Demo2: The password field is required.

 var response = { "errors": { "password": [ "The password field is required.", "The password is too short." ] } } alert(response.errors[Object.keys(response.errors)[0]][0]); 

Demo3: The password is too short.

 var response = { "errors": { "password": [ "The password is too short." ] } } alert(response.errors[Object.keys(response.errors)[0]][0]); 

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