简体   繁体   中英

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 })


输出

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

Your function is design for an object not for a Map . 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM