Search code examples
javascriptapiecmascript-2016

Get iteration number in for...of loop while iterating over an object JavaScript


I am getting the following object from API call:

{
    "email": ["The email has already been taken."],
    "profile_image": [ "profile image is requried." ]
}

I used the following code to iterate over this object (using for...of):

let message = "";
for (const [error_name, error_value, i] of Object.entries(
  error.response.data.errors
)) {
  message += `${i}: ${error_value[0]}\n`;
}

But I am getting undefined instead of getting the value of i. I want to get the iteration number.

Any suggestions?


Solution

  • An Object.entries item will only contain two values: the key and the value. If you want the index as well, you'll have to implement it yourself or use another strategy. One option is use forEach to iterate over the array instead (the second argument forEach takes is the current index):

    let message = "";
    Object.entries(error.response.data.errors)
      .forEach(([error_name, error_value], i) => {
        message += `${i}: ${error_value[0]}\n`;
      });
    

    You can also avoid the let for message by using .map/.join:

    const message = Object.entries(error.response.data.errors)
      .map(([error_name, error_value], i) => `${i}: ${error_value[0]}`)
      .join('\n');
    

    (unlike your original code, this will not have a trailing newline at the end, but that's probably a good thing)