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

如何使用JavaScript过滤分组嵌套对象,按行业分类工作经历数据

实现方案

直接用原生JavaScript的数组方法即可完成分组,无需引入第三方依赖,实现代码如下:

const dataWork = [
  {
    _id:1,
    firstName:'Leo',
    lastName:'Bla',
    mail:'leo.bla@gmail.com',
    certifications:[
      {_id:1, certification:'C1 Certification'},
      {_id:2, certification:'C3 Certification'}
    ],
    education:[
      {_id:1, school:'School A'}
    ],
    work:[
      {_id:1, company:'Company A', industry:'Industry A'},
      {_id:2, company:'Company B', industry:'Industry B'},
      {_id:3, company:'Company A', industry:'Industry A'},
      {_id:4, company:'Company C', industry:'Industry C'},
      {_id:5, company:'Company C', industry:'Industry C'},
      {_id:6, company:'Company B', industry:'Industry A'},
      {_id:7, company:'Company D', industry:'Industry B'},
    ]
  }
];

const result = dataWork.map(userItem => {
  const industryGroup = {};
  // 遍历当前用户的所有工作经历
  userItem.work.forEach(workRecord => {
    // 生成符合要求的分组key:将Industry A转换为industryA格式
    const groupKey = workRecord.industry
      .replaceAll(' ', '')
      .replace(/^./, firstChar => firstChar.toLowerCase());
    // 分组不存在则初始化空数组
    if (!industryGroup[groupKey]) industryGroup[groupKey] = [];
    // 存入当前工作记录,如果不需要保留industry字段,可替换为下面两行代码
    // const { industry, ...restRecord } = workRecord;
    // industryGroup[groupKey].push(restRecord);
    industryGroup[groupKey].push(workRecord);
  });
  return industryGroup;
});

逻辑说明

  • 用map遍历原始数据的每一个用户条目,保证输出结构外层为数组,每个元素对应用户的分组结果
  • 遍历每个用户的work数组,以industry字段为基准生成驼峰格式的分组键
  • 同行业的工作记录会被归集到同一个数组下,最终输出和你要求的结构完全一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 10:06:03