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

查看:58
本文介绍了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天全站免登陆