[removed] Object Rename Key

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

    Your way is optimized, in my opinion. But you will end up with reordered keys. Newly created key will be appended at the end. I know you should never rely on key order, but if you need to preserve it, you will need to go through all keys and construct new object one by one, replacing the key in question during that process.

    Like this:

    var new_o={};
    for (var i in o)
    {
       if (i==old_key) new_o[new_key]=o[old_key];
       else new_o[i]=o[i];
    }
    o=new_o;
    

提交回复
热议问题