Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

javascript - JavaScript:对象重命名键(JavaScript: Object Rename Key)

Is there a clever (ie optimized) way to rename a key in a javascript object?(是否有一种巧妙(即优化)的方法来重命名javascript对象中的键?)

A non-optimized way would be:(一种非优化的方式是:) o[ new_key ] = o[ old_key ]; delete o[ old_key ];   ask by Jean Vincent translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.(此方法确保重命名的属性的行为与原始属性相同 。) 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.(另外,在我看来,将其包装到函数/方法中并将其放入Object.prototype与您的问题无关。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...