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

如何在JavaScript中按empId、salDate双字段对对象数组进行分组

你可以直接使用JavaScript数组的reduce方法完成层级分组,实现代码如下:

// 你的原始薪资数组
const salaryData = [
  {
    "id": 5308,
    "empId": 202,
    "loc": 1,
    "salMonth": "1",
    "salYear": "2020",
    "salDate": "2020-01",
    "netSal": 50000
  },
  {
    "id": 5309,
    "empId": 173,
    "loc": 1,
    "salMonth": "1",
    "salYear": "2020",
    "salDate": "2020-01",
    "netSal": 30000
  },
  {
    "id": 5310,
    "empId": 212,
    "loc": 1,
    "salMonth": "1",
    "salYear": "2020",
    "salDate": "2020-01",
    "netSal": 21100
  },
  {
    "id": 5311,
    "empId": 163,
    "loc": 1,
    "salMonth": "1",
    "salYear": "2020",
    "salDate": "2020-01",
    "netSal": 43000
  },
  {
    "id": 5312,
    "empId": 116,
    "loc": 1,
    "salMonth": "1",
    "salYear": "2020",
    "salDate": "2020-01",
    "netSal": 52000
  },
  {
    "id": 5313,
    "empId": 223,
    "loc": 1,
    "salMonth": "1",
    "salYear": "2020",
    "salDate": "2020-01",
    "netSal": 21100
  },
  {
    "id": 5314,
    "empId": 231,
    "loc": 1,
    "salMonth": "1",
    "salYear": "2020",
    "salDate": "2020-01",
    "netSal": 42217
  }
]

// 层级分组逻辑
const groupedSal = salaryData.reduce((result, item) => {
  const empKey = item.empId
  const dateKey = item.salDate
  // 不存在对应员工则初始化层级
  if (!result[empKey]) {
    result[empKey] = {}
  }
  // 赋值薪资信息
  result[empKey][dateKey] = {
    salId: item.id,
    salary: item.netSal
  }
  return result
}, {})

// 打印查看结果
console.log(JSON.stringify(groupedSal, null, 2))

上述代码执行后得到的groupedSal就是你要求的输出结构。如果存在同一员工同一月份有多条薪资记录的场景,你可以自行调整赋值逻辑,比如将同日期的薪资数据存为数组,或者按照规则合并数据即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 09:54:08