[removed] Object Rename Key

前端 未结 24 1404
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 00:18

Is there a clever (i.e. optimized) way to rename a key in a javascript object?

A non-optimized way would be:

o[ new_key ] = o[ old_key ];
delete o[ o         


        
24条回答
  •  别那么骄傲
    2020-11-22 00:57

    just try it in your favorite editor <3

    const obj = {1: 'a', 2: 'b', 3: 'c'}
    
    const OLD_KEY = 1
    const NEW_KEY = 10
    
    const { [OLD_KEY]: replaceByKey, ...rest } = obj
    const new_obj = {
      ...rest,
      [NEW_KEY]: replaceByKey
    }
    

提交回复
热议问题