skip to Main Content

I have a JSON like this: they are errors I need to print the error what happened error1, or error2 or error3 and so on

errors = {deployer: ['error1'],
 discard: ['error2'],
 worker: ['error3']
...}

sometimes they are only deployer or only discard or only worker or all or two of them, but I don’t know what kind of error is going to happen.

2

Answers


  1. This will map through the erros object keys and log the corresponding value for each key if it is not an empty array:

    const errors = {
      deployer: ['error1'],
      discard: ['error2'],
      worker: ['error3']
      // ...
    };
    
    for (const key in errors) {
      if (errors[key].length > 0) {
        console.log(`${key}: ${errors[key]}`);
      }
    }
    

    you can use ${errors[key].join(', ')} to join all the values inside the array if they are all string

    Login or Signup to reply.
  2. You can use Object.values() to get all the values of the object without knowing the keys. Then, for each array in those values, you can use the spread operator to print all elements of each error array.

    const errors = {
        deployer: ['error1'],
        discard: ['error2'],
        worker: ['error3']
    };
    
    Object.values(errors).forEach((e) => {
        console.log(...e);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search