First of all I’m beginner in javascript. I have this data data.responseJSOn.errors –
Currently I’m displaying the errors like this way –
var errors = data.responseJSON.errors;
console.log(errors);
errors.title &&
errors.title.forEach(function(messageText) {
displayError(messageText);
});
errors.message &&
errors.message.forEach(function(messageText) {
displayError(messageText);
});
How can I display errors from there by using single code instead of predefined errors.title or errors.message.
expected code like –
var errors = data.responseJSON.errors;
var list = ["title", "message"];
list.forEach(function(item) {
errors.item &&
errors.item.forEach(function(messageText) {
displayError(messageText);
});
});
How can I fix it to get output.
4
Answers
In the case you’re going to need the
[]
syntax to access a field of theerrors
object with the value of a variable:You can access the respective property using
[]
:Otherwise (and as a better alternative), you can use the
for...in
loop syntax to access enumerable object properties:You can try something more generic regardless of the key names in object
data.responseJSON.errors
here you don’t have to explicitly mention the type of keys the error message has. Even in future, if
messages
andtitle
changes you don’t have to modify the code again.