迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

如何在 JavaScript 中重命名对象的键

作者:迹忆客 最近更新:2022/12/02 浏览次数:

JavaScript 中要重命名对象中的键:

  1. 使用括号表示法将旧密钥的值分配给新密钥。
  2. 使用删除运算符删除旧密钥。
  3. 该对象将仅包含具有新名称的键。
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 属性。

我个人的偏好是使用第一种方法。 第二种方法实现了相同的目标,但是它更间接并且更难阅读。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

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 POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便