0

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?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Dustin
  • 567
  • 2
  • 5
  • 18

3 Answers3

2

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

Rayon
  • 36,219
  • 4
  • 49
  • 76
1

Problems here for in will give you the key not data try for of or err.errors[error]

trquoccuong
  • 2,857
  • 2
  • 20
  • 26
1

Try iterating obj.err.errors.username

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

for (var error in obj.err.errors.username) {
  if (error === "message")
    messages.push(obj.err.errors.username[error])
}

console.log(messages)
guest271314
  • 1
  • 15
  • 104
  • 177