Wonka Wonka - 4 months ago 20
Javascript Question

React Native - alert first item in object's arrays using .map?

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. I tried using RN's map function, but wasn't able to get it to work as intended below.

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?

Answer

considering this is the respone:

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

this will do the trick

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

in your case replace respone with results.body

Demo 1: The username field is required.

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

alert(respone.errors[Object.keys(respone.errors)[0]][0]);

Demo2: The password field is required.

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

alert(respone.errors[Object.keys(respone.errors)[0]][0]);

Demo3: The password is too short.

var respone = {
  "errors": {
    "password": [
      "The password is too short."
    ]
  }
}

alert(respone.errors[Object.keys(respone.errors)[0]][0]);

Comments