Express response includes deleted key from Typescript array

Issue

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

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.

Answered By – Scott Christopher

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published