'Express response includes deleted key from Typescript array

I am having difficulty removing the assetId key from every element in my array.

type Video = {
  assetId?: string
  description: string
  publishedDate: string
  slug: string
  title: string
  uuid: string
}

const list = asyncHandler(async (req: Request, res: Response, _: NextFunction) => {
  const videos = (await findVideos()) as Video[]
  const rVideos = R.forEach(R.dissoc('assetId'))(videos)
  res.status(200).json({ status: 'ok', count: videos.length, data: { rVideos } })
})

This does not work as the JSON body response is a list of Video that still contain assetId.

Here is another attempt:

const list = asyncHandler(async (req: Request, res: Response, _: NextFunction) => {
  const videos = (await findVideos()) as Video[]
  const rVideo = videos[0]
  delete rVideo['assetId']
  res.status(200).json({ status: 'ok', count: videos.length, data: { rVideo } })
})

Even still, the response contains a single video that has assetId in it!

In fact, I cannot even figure out how to remove an object key (assetId) for an Express response.



Solution 1:[1]

Note that functions in Ramda never mutate the original data structures, so R.forEach is intended to iterate over the array and run some side-effecting function for each element, then return the original array.

Similarly, R.dissoc doesn't mutate the original object. It instead creates a new object without the key. So this new object is effectively discarded when run within R.forEach.

Try changing your example from:

R.forEach(R.dissoc('assetId'))(videos)

to:

R.map(R.dissoc('assetId'), videos)

Utilising R.map will produce and return a new array with the modified objects, rather than the original array.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Scott Christopher