[removed] Object Rename Key

前端 未结 24 1387
爱一瞬间的悲伤
爱一瞬间的悲伤 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 01:09

    If you're mutating your source object, ES6 can do it in one line.

    delete Object.assign(o, {[newKey]: o[oldKey] })[oldKey];
    

    Or two lines if you want to create a new object.

    const newObject = {};
    delete Object.assign(newObject, o, {[newKey]: o[oldKey] })[oldKey];
    

提交回复
热议问题