Dustin Dustin - 5 years ago 139
Javascript Question

Confused about iterating nested objects

so I have the following object:

{ err:
{ message: 'Validation failed',
name: 'ValidationError',
errors:
{ username:
{ properties: [Object],
message: 'Path `username` is required.',
name: 'ValidatorError',
kind: 'required',
path: 'username',
value: '' } } } }


I am trying to iterate over
err.errors
and push for example
err.errors.username.message
into an array:

for(var error in err.errors){
messages.push(error.message);
}


Doing this is just pushing null into my
messages
array. So to troubleshoot I have tried to
console.log(typeof error);
which gives me a
string
. This is what is confusing because, when I call
typeof
on
err.errors.username
it outputs
object
, yet calling it inside of the loop it produces
string
...

So what is going on here?

Answer Source

You are accessing key from object which is anotherobject.errorinfor-inwill returnkey->usernamehence you need to access that key from object and thenmessagefrom thatusername` object.

Try this:

var obj = {
  err: {
    message: 'Validation failed',
    name: 'ValidationError',
    errors: {
      username: {
        properties: [Object],
        message: 'Path `username` is required.',
        name: 'ValidatorError',
        kind: 'required',
        path: 'username',
        value: ''
      },
      password: {
      properties: [Object],
      message: 'Path `password` is required.',
      name: 'ValidatorError',
      kind: 'required',
      path: 'password',
      value: ''
      }
    }
  }
};
var messages = [];
for (var error in obj.err.errors) {
  messages.push(obj.err.errors[error].message);
}
alert(messages);

Fiddle here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download