[removed] Object Rename Key

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

    Personally, the most effective way to rename keys in object without implementing extra heavy plugins and wheels:

    var str = JSON.stringify(object);
    str = str.replace(/oldKey/g, 'newKey');
    str = str.replace(/oldKey2/g, 'newKey2');
    
    object = JSON.parse(str);
    

    You can also wrap it in try-catch if your object has invalid structure. Works perfectly :)

提交回复
热议问题