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?

felixmosh
  • 32,615
  • 9
  • 69
  • 88
Jonathan Lightbringer
  • 435
  • 2
  • 12
  • 27
  • Possible duplicate of [Angular2 - \*ngFor / loop through json object with array](https://stackoverflow.com/questions/43215049/angular2-ngfor-loop-through-json-object-with-array) – Vivek Doshi Feb 16 '18 at 13:20

2 Answers2

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);
felixmosh
  • 32,615
  • 9
  • 69
  • 88
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)
Rakesh Chand
  • 3,105
  • 1
  • 20
  • 41