skip to Main Content

First of all I’m beginner in javascript. I have this data data.responseJSOn.errors

enter image description here

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


  1. In the case you’re going to need the [] syntax to access a field of the errors object with the value of a variable:

    var errors =  data.responseJSON.errors;
    var list = ["title", "message"];
    
    list.forEach(function(item) {
        errors[item] && 
        errors[item].forEach(function(messageText) {
            displayError(messageText);
        });
    });
    
    Login or Signup to reply.
  2. You can access the respective property using []:

    var errors =  data.responseJSON.errors;
    var list = ["title", "message"];
    
    list.forEach(function(item) {
        errors[item] && 
        errors[item].forEach(function(messageText) {
            displayError(messageText);
        });
    });
    

    Otherwise (and as a better alternative), you can use the for...in loop syntax to access enumerable object properties:

    var errors =  data.responseJSON.errors;
    var list = ["title", "message"];
    
    errors.forEach(function(error) {
        for (property in error) {
            displayError(error[property]);
        }
    });
    
    Login or Signup to reply.
  3. You can try something more generic regardless of the key names in object data.responseJSON.errors

    var errors =  data.responseJSON.errors;
    var list = ["title", "message"]; // valid keys for which we need to show message
    
    for (key in errors) {
      // check if key is valid and is array
      if(list.includes(key) && Array.isArray(errors[key])) {
        errors[key].map((msg) => {
            displayError(msg);
        })
      } 
    }
    
    Login or Signup to reply.
  4. here you don’t have to explicitly mention the type of keys the error message has. Even in future, if messages and title changes you don’t have to modify the code again.

    const messageText = (message: string) => {
      console.log('message', message)
    }
    
    Object.keys(response).map((error) => response[error].length && response[error].forEach((message: string) =>  messageText(message)));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search