如何在 JavaScript 中重命名对象的键
JavaScript 中要重命名对象中的键:
- 使用括号表示法将旧密钥的值分配给新密钥。
- 使用删除运算符删除旧密钥。
- 该对象将仅包含具有新名称的键。
const obj = {oldKey: 'value'};
obj['newKey'] = obj['oldKey'];
delete obj['oldKey'];
console.log(obj); // 👉️ {newKey: 'value'}
我们使用括号 []
表示法将 oldKey 的值分配给对象中的 newKey 属性。
最后一步是使用 delete
运算符从对象中删除旧键。
这实际上重命名了对象中的键。
如果对象中键的名称不包含空格或以特殊字符开头,您也可以使用点表示法。
const obj = {oldKey: 'value'};
obj.newKey = obj.oldKey;
delete obj.oldKey;
console.log(obj); // 👉️ {newKey: 'value'}
此代码片段实现了相同的结果,并且更加简洁。 但是,使用点表示法访问对象属性时存在的一些限制不适用于方括号 []
表示法访问。
另一种但也是非常常见的方法是使用 Object.assign
方法。
const obj = {oldKey: 'value'};
delete Object.assign(obj, {newKey: obj.oldKey})['oldKey'];
console.log(obj); // 👉️ {newKey: 'value'}
Object.assign 方法有两个参数:
- 目标对象 - 应用源属性的对象
- 源对象 - 包含要应用于目标对象的属性的源对象。
该方法返回应用了提供的属性的目标对象。
我们将 newKey 属性添加到对象并将其设置为 oldKey 属性的值。
最后一步是使用删除运算符删除 oldKey 属性。
我个人的偏好是使用第一种方法。 第二种方法实现了相同的目标,但是它更间接并且更难阅读。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。