JavaScript:对象重命名密钥 [英] JavaScript: Object Rename Key

查看:168
本文介绍了JavaScript:对象重命名密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种聪明的(即优化的)方法来重命名javascript对象中的键?

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

非优化的方式是:

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


推荐答案

最完整(也是正确)的做法我会相信:

The most complete (and correct) way of doing this would be, I believe:

if (old_key !== new_key) {
    Object.defineProperty(o, new_key,
        Object.getOwnPropertyDescriptor(o, old_key));
    delete o[old_key];
}

此方法可确保重命名的属性行为相同原来的。

This method ensures that the renamed property behaves identically to the original one.

另外,在我看来,可以将它包装成函数/方法并将其放入 Object.prototype 与您的问题无关。

Also, it seems to me that the possibility to wrap this into a function/method and put it into Object.prototype is irrelevant regarding your question.

这篇关于JavaScript:对象重命名密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆