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

基于条件重命名JavaScript对象键的ES6/ES7实现方案

根据operation字段动态重命名对象键的ES6实现

完全可以用ES6的数组方法配合解构赋值实现,不用写显式的for循环,代码简洁高效:

示例代码

假设你的原始数据数组如下:

const originalList = [
  { operation: 'DELETE', idmuFlag: 'del-101', desc: '删除项1' },
  { operation: 'UPDATE', idmuFlag: 'upd-202', desc: '更新项2' },
  { operation: 'DELETE', idmuFlag: 'del-303', desc: '删除项3' }
];

转换逻辑代码:

const transformedList = originalList.map(item => {
  // 解构拆分出需要处理的字段和剩余属性
  const { idmuFlag, operation, ...restProps } = item;
  // 根据operation值确定目标键名
  const targetKey = operation === 'DELETE' ? 'idm' : 'idmNew';
  // 重构新对象,合并剩余属性、operation和新键值对
  return { ...restProps, operation, [targetKey]: idmuFlag };
});

代码说明

  • 用map()遍历数组,自动处理每个元素,替代手动for循环
  • 解构赋值直接拆分出idmuFlag、operation和其他剩余属性,无需手动逐个访问对象属性
  • 利用计算属性名[targetKey]动态设置新键,一步完成重命名,省去了先赋值新键再删除旧键的冗余操作
  • 最终返回全新的对象数组,不会修改原始数据,避免了副作用,符合函数式编程的最佳实践

如果确实需要修改原数组(不推荐,会污染原始数据),也可以用forEach配合解构实现:

originalList.forEach(item => {
  const { idmuFlag, operation } = item;
  const targetKey = operation === 'DELETE' ? 'idm' : 'idmNew';
  item[targetKey] = idmuFlag;
  delete item.idmuFlag;
});

但更推荐返回新数组的方式,代码可维护性更高,也避免了意外修改原始数据的风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 20:20:58