Home > Web Front-end > JS Tutorial > How Can I Efficiently Rename Keys in a JavaScript Object?

How Can I Efficiently Rename Keys in a JavaScript Object?

Susan Sarandon
Release: 2024-12-15 00:38:10
Original
789 people have browsed it

How Can I Efficiently Rename Keys in a JavaScript Object?

Efficient JavaScript Object Key Renaming

Renaming keys in a JavaScript object can be done using the following non-optimized method:

o[ new_key ] = o[ old_key ];
delete o[ old_key ];
Copy after login

However, a more optimal approach involves preserving the original property behavior:

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

This method ensures that the renamed property behaves identically to the original one. It inherits all attributes such as accessibility and mutability.

While wrapping this into a function/method and adding it to the Object.prototype is possible, it is not directly relevant to the question of optimal key renaming.

The above is the detailed content of How Can I Efficiently Rename Keys in a JavaScript Object?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template