0

Given this JavaScript snipped (not TypeScript!). How can we use map instead of a loop?

import { serialize } from 'next-mdx-remote/serialize'
...
const helperArray = []
for (const element of arrayOfObjects) {
  helperArray.push({ ...element, description: await serialize(element.description)})
}

Thanks!

Stefan
  • 576
  • 7
  • 27
  • 2
    You could try [`const helperArray = await Promise.all(arrayOfObjects.map(async (`…`) =>`…`))`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all). – Sebastian Simon Dec 20 '22 at 22:49
  • Thanks for the prompt answers. I'll check the information. Probably this answers my question already. Have to think a little bit. – Stefan Dec 20 '22 at 22:57
  • 1
    This solution uses two array map methods, but it should work out fine, as long as you use it in an async function: const promiseArray = arrayOfObjects.map((element) => { return serialize(element.description) }) await Promise.allSettled(promiseArray) const resultArray = arrayOfObjects.map((element, index) => { return { ...element, description: promiseArray[index]} }) – JCollier Dec 20 '22 at 23:03
  • 1
    Someone closed the question right before I could answer. Sorry for the lousy formatting. – JCollier Dec 20 '22 at 23:03

0 Answers0