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

将员工对象数组中部门字符串转换为对应ID值(基于部门数组)

高效转换员工部门字段为对应ID的方案

嘿,这个需求在处理关联数据时挺常见的,我给你一个简洁又高效的实现方式,尤其是当数据量比较大的时候,性能优势会很明显:

第一步:先做个部门映射表

首先我们把departments数组转换成一个键值对对象,这样就能O(1)时间快速查找部门对应的ID,不用每次遍历整个部门数组:

const deptMap = departments.reduce((map, dept) => {
  map[dept.dep] = dept.id;
  return map;
}, {});

这个映射表最终会是这样的结构:

{
  sales: 12,
  "quality assurance": 11,
  inventory: 13 // 假设你补全了这个ID
}

第二步:转换员工数组

接下来遍历员工数组,把每个员工的department字符串替换成对应的ID就行。这里用对象展开运算符创建新对象,不会修改原数组,保持数据不可变性:

const transformedEmployees = employees.map(emp => ({
  ...emp,
  department: deptMap[emp.department]
}));

完整可运行代码

把所有代码整合起来,包括你的原始数组(我补全了inventory的ID示例):

const employees = [ 
  { name: 'bob', department: 'sales', location: 'west' }, 
  { name:'fred', department: 'sales', location: 'west' }, 
  { name:'josh', department: 'inventory', location: 'east' }, 
  { name: 'mike', department: 'quality assurance', location: 'north' } 
];
const departments = [ 
  { dep: 'sales', id: 12 }, 
  { dep:'quality assurance', id: 11 }, 
  { dep:'inventory', id: 13 }
];

// 构建部门ID映射
const deptMap = departments.reduce((map, dept) => {
  map[dept.dep] = dept.id;
  return map;
}, {});

// 转换员工数据
const transformedEmployees = employees.map(emp => ({
  ...emp,
  department: deptMap[emp.department]
}));

// 查看结果
console.log(transformedEmployees);

最终输出

运行后你会得到转换后的员工数组:

[
  { name: 'bob', department: 12, location: 'west' },
  { name: 'fred', department: 12, location: 'west' },
  { name: 'josh', department: 13, location: 'east' },
  { name: 'mike', department: 11, location: 'north' }
]

小提示

如果担心有员工的部门不在映射表里(会得到undefined),可以加个默认值处理,比如:

department: deptMap[emp.department] ?? 'Unknown Department'

用??空值合并运算符只会在值为null或undefined时生效,比||更严谨哦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:47:29