0

I have a JSON that looks like this:

{
"success": false,
"error": {
    "username": [
        "The username has already been taken."
    ],
    "email_address": [
        "The email address has already been taken."
    ]
}
}

I want to store all the messages in an array. Right now, I'm doing it manually by checking one by one. Is there a better way?

1

2 Answers 2

1

You can use the Object.keys method that will return an array with the error keys. Then you can iterate it with any Array method such as map, forEach, reduce to collect the messages them-self.

const response = {
  "success": false,
  "error": {
    "username": [
      "The username has already been taken.",
      "Another message"
    ],
    "email_address": [
      "The email address has already been taken."
    ]
  }
};

const result = Object.keys(response.error)
  .reduce((acc, key) => acc.concat(response.error[key]), []);

console.log(result);

Sign up to request clarification or add additional context in comments.

3 Comments

Undefined values are stored in array, although the number is right.
So, I would use reduce in order to collect all the messages. will update my answer
Works like charm.
0

This is how you can get all the messages in a array

var a = {
"success": false,
"error": {
    "username": [
        "The username has already been taken."
    ],
    "email_address": [
        "The email address has already been taken."
    ]
}
}
var keys = Object.keys(a['error'])
var errors = a['error']

var c = [];
for(var i=0; i< keys.length; i++){
    c.push(a['error'][keys[i]][0])
}
console.log(c)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.