How do I rename a key in a Map Object, while keeping the value and the other keys and values the same?

bookMap = new Map()
bookMap = Map(3) {
  'Horror': [
    { id: 9798721052927, title: 'Dracula', author: 'Brahm Stoker' },
    { id: 9798721052928, title: 'Dracula 2', author: 'Brahm Stoker' }
  ],
  'Romance': [
    { id: 9798721052933, title: 'Love Story', author: 'Brahm Stoker' }
  ],
  'Comedy': [ { id: 9797221052931, title: 'Ha Story', author: 'Brahm Stoker' } ]
}

const renameKey = (oldKey, newKey, { [oldKey]: old, ...others }) => ({
  [newKey]: old,
  ...others
})

nbm = renameKey('Horror', 'Cusisine', { ['Horror']: bookMap.get('Horror'), ...bookMap })


output

What do I put as …others to get the ouput as bookMap with all 3 keys, not just the newly changed one?

Answer

Your function is designed for an object, not for a Map. A map destructured into an array of arrays. If you want to achieve the same functionality you can use a method like below :

const renameKey = (oldKey: string, newKey: string, map: Map<string, any>) => {
  const old = map.get(oldKey);
  const rest = [...map].filter(r => r[0] !== oldKey);
  return new Map(
    [[newKey, old],
    ...rest]);
}

Playground