0

I have a variable with some data (key/value):

var errors = JSON.parse(xhr.responseText);

Here is the content:

 {
 "vehicle.Model":"Le champ Model est requis.",
 "vehicle.Brand":"Le champ Brand est requis.",
 "vehicle.Registration":"Le champ Registration est requis."
 }

I would like to loop into it and display the key and the value for each.

How to proceed?

Thanks.

0

3 Answers 3

1
var key;

for (key in errors) {
   if (errors.hasOwnProperty(key)) {
      console.log(key + " : " + errors[key]);
   }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Don't use hasOwnProperty if you just got the object using JSON.parse.
always check the 'hasOwnProperty' so you dont end up in the prototype chain.
Always using hasOwnProperty is a good practice IMO, regardless of where the data is coming from, although this is not mandatory here. Code review and further maintenance / evolution will be easier.
0
for (var key in errors) {
   var code = key;
   var label = errors[key];
   ...
}

Note that there is no guarantee regarding the iteration order in today's ECMAScript.

I'd recommend you to read MDN's Working with objects.

1 Comment

You're not using the code variable (it seems useless anyway).
0
for( key in errors ){console.log(key + " = " + errors.key);}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.