How to use async package async.forEach with an object with Node.js?

Sometimes, we want to use async package async.forEach with an object with Node.js.

In this article, we’ll look at how to use async package async.forEach with an object with Node.js.

How to use async package async.forEach with an object with Node.js?

To use async package async.forEach with an object with Node.js, we can use the Object.entries method to return an array of key-value pair arrays from the object.

For instance, we write

async.forEach(
  Object.entries(dataObj),
  ([key, val], callback) => {
    console.log(key, val);
    callback();
  },
  (err) => {
    console.log("iterating done");
  }
);

to call async.forEach with the array of key-value pair arrays returned from Object.entries called with dataObj to iterate through the key-value pair array.

In the first callback, we get the key and val values from the key-value pair array being iterated through.

Then callback is called in the callback to do something with the entry.

The 2nd callback is run when iteration is done.

Conclusion

To use async package async.forEach with an object with Node.js, we can use the Object.entries method to return an array of key-value pair arrays from the object.