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

如何基于指定属性值动态拆分对象数组?

按指定属性动态分组对象数组

这是个很常见的数组处理需求,我们可以用JavaScript的reduce方法来实现这个通用的分组函数,简洁又高效。

实现代码

function solution(arr, groupByKey) {
  return arr.reduce((acc, current) => {
    // 获取当前元素的分组键值
    const key = current[groupByKey];
    // 如果当前键还没在累加器里,先初始化一个空数组
    if (!acc[key]) {
      acc[key] = [];
    }
    // 把当前元素push到对应分组的数组中
    acc[key].push(current);
    return acc;
  }, {}); // 初始累加器是一个空对象
}

测试你的示例输入

const input = [ 
  {"name": "john", "location": "first"}, 
  {"name": "steve", "location": "first"}, 
  {"name": "paul", "location": "another"}, 
  {"name": "tony", "location": "random"}, 
  {"name": "ant", "location": "random"} 
];

console.log(solution(input, 'location'));

输出结果

{
  first: [
    {"name": "john", "location": "first"},
    {"name": "steve", "location": "first"}
  ],
  another: [{"name": "paul", "location": "another"}],
  random: [
    {"name": "tony", "location": "random"},
    {"name": "ant", "location": "random"}
  ]
}

可选扩展:处理属性缺失的情况

如果数组里有些对象没有指定的分组属性,可以给它们设置一个默认分组,比如'unknown':

function solution(arr, groupByKey, defaultKey = 'unknown') {
  return arr.reduce((acc, current) => {
    const key = current[groupByKey] ?? defaultKey;
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(current);
    return acc;
  }, {});
}

这样就算遇到缺失目标属性的对象,也会被分到指定的默认组里,避免出现undefined键的混乱情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:49:04