1

I have a response coming back from my server that looks like this

{"Errors":{"ViewModels[0]":"Not a valid number."},"IsValid":false,"SuccessMessage":null}

I want to loop through all the values contrained in Errors(in this case there is only one but there could many).

I tried

   function createErrorList(response)
    {
        for (var i = 0; i < response.Errors.length; i++)
        {
            var error = response.Errors[i];
            alert(error);
        }
    }

length is alwasy undefined though. So I am not sure what I am doing wrong.

chobo2
  • 83,322
  • 195
  • 530
  • 832
  • Do you have an example with two errors? This is an object returned (no length element), it's not clear if it'll continue to be an object (element 1: "ViewModels[0]" element 2: "ViewModels[1]") or if it'll switch into an array. – Rudu Mar 16 '11 at 19:51

3 Answers3

1

Errors is not an array it's an object in this case. The server response would have to be something like:

{"Errors":[{"ViewModels[0]":"Not a valid number."},{"viewmodels[1]":"Another Message"}],"IsValid":false,"SuccessMessage":null}

For that to work. Note the [].

for( var key in response.Errors ) {
  var value = response.Errors[key];
}
Justin Thomas
  • 5,680
  • 3
  • 38
  • 63
0

response.Errors is a dictionary not a list so you have to iterate through as such

Dan D.
  • 73,243
  • 15
  • 104
  • 123
  • How could I iterate through it? Could I get the values by index. So I don't have to call up the key name? I probably won't no the keyname. – chobo2 Mar 16 '11 at 19:48
  • See http://stackoverflow.com/questions/890807/iterate-over-a-javascript-associative-array-in-sorted-order – Dan D. Mar 16 '11 at 19:51
0
for (var error in response.Errors)
{
    alert(response.Errors[error]);
}

You may also want to include hasOwnProperty if you are paranoid about prototypes on the Object object.

Plynx
  • 11,341
  • 3
  • 32
  • 33
  • did not know you could make a for loop look like that in javascript. What is [error] are you using the one from the for? – chobo2 Mar 16 '11 at 19:52
  • It's a variable like i in your for loop. Instead of getting populated with numbers, it is populated with each key in the key-value pairs of the object. Putting for (var error in ... ) is probably safer since it makes sure it's a local variable. – Plynx Mar 16 '11 at 19:53
  • 1
    it is also slower: see my citation for this note: http://blogs.sun.com/greimer/entry/best_way_to_code_a – Mark Schultheiss Mar 16 '11 at 20:11