You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript如何返回新对象实现对象键名翻译?

如何返回键名翻译后的新对象而不修改原对象?

你的问题出在直接修改了传入的原对象,同时尝试的new Object(student)并没有创建真正独立的新对象——它本质上还是引用了原对象的内存地址,所以修改副本时原对象也会被改动。下面是几种可靠的实现方式:

方法一:使用对象解构与展开运算符(推荐)

这是最简洁直观的写法,通过解构分离出需要替换的键,再用展开运算符构建新对象:

function translateKey(student, keyToChange, translation) {
  // 解构出目标键的值,剩余属性存入rest对象
  const { [keyToChange]: targetValue, ...rest } = student;
  // 构建并返回新对象,合并剩余属性与翻译后的键值对
  return { ...rest, [translation]: targetValue };
}

const student = {
  firstName: "Napoleon",
  surname: "Bonaparte",
  ilsSontMorts: true,
};

// 得到新对象,原对象不受影响
console.log(translateKey(student, "ilsSontMorts", "isDead"));
// 验证原对象未被修改
console.log(student);

方法二:使用Object.assign创建副本

通过Object.assign创建原对象的浅拷贝,再在副本上修改键名:

function translateKey(student, keyToChange, translation) {
  // 创建原对象的独立副本
  const newStudent = Object.assign({}, student);
  // 添加翻译后的键值对
  newStudent[translation] = newStudent[keyToChange];
  // 删除旧键
  delete newStudent[keyToChange];
  return newStudent;
}

两种方法都能保证返回全新的对象,且不会修改传入的原student对象,符合你的需求。

内容的提问来源于stack exchange,提问作者Vincenzo Chiovaro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 19:01:12