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

如何在JavaScript中将同职业人员归类到新创建的对象中?

问题:按职业归类数组中的人员数据

我需要将数组内同职业的人员归类到result对象中,但现有代码无法正确保留所有数据。

原始数据

const data = [
    {
        Name: 'Smith',
        age: 25,
        profession: 'Banker'
    },
    {
        Name: 'Alex',
        age: 28,
        profession: 'IT'
    },
    {
        Name: 'John',
        age: 31,
        profession: 'Banker'
    },
    {
        Name: 'Harry',
        age: 26,
        profession: 'Nurse'
    },
];
const result = {};

当前代码

const data = [ { Name: "Smith", age: 25, profession: "Banker" }, { Name: "Alex", age: 28, profession: "IT" }, { Name: "John", age: 31, profession: "Banker" }, { Name: "Harry", age: 26, profession: "Nurse" } ];

const result = {};
data.forEach(({ Name, age, profession }) => {
  result[profession] = { Name, age };
});
console.log(result);

问题原因

当前代码每次循环都会直接覆盖result[profession]的取值,导致同一职业下只有最后一条人员数据被保留。比如Banker职业,最终只留下John的数据,Smith的数据被覆盖丢失。

解决方案

方法一:使用forEach处理数组

先检查当前职业对应的属性是否存在,不存在则初始化为空数组,再将当前人员数据推入对应数组:

const data = [
    { Name: 'Smith', age: 25, profession: 'Banker' },
    { Name: 'Alex', age: 28, profession: 'IT' },
    { Name: 'John', age: 31, profession: 'Banker' },
    { Name: 'Harry', age: 26, profession: 'Nurse' }
];

const result = {};
data.forEach(({ Name, age, profession }) => {
  if (!result[profession]) {
    result[profession] = [];
  }
  result[profession].push({ Name, age });
});
console.log(result);

方法二:使用Array.reduce(更简洁)

利用reduce方法直接构建结果对象:

const data = [
    { Name: 'Smith', age: 25, profession: 'Banker' },
    { Name: 'Alex', age: 28, profession: 'IT' },
    { Name: 'John', age: 31, profession: 'Banker' },
    { Name: 'Harry', age: 26, profession: 'Nurse' }
];

const result = data.reduce((acc, { Name, age, profession }) => {
  acc[profession] = acc[profession] || [];
  acc[profession].push({ Name, age });
  return acc;
}, {});

console.log(result);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 05:36:13