Jonathan Lightbringer
Jonathan Lightbringer

Reputation: 574

How do I loop through json with arrays and get all the value?

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?

Upvotes: 0

Views: 53

Answers (2)

felixmosh
felixmosh

Reputation: 35593

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);

Upvotes: 1

Rakesh Chand
Rakesh Chand

Reputation: 3113

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)

Upvotes: 0

Related Questions