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

如何遍历数组并按匹配的account值将元素分组到新对象

根据account字段动态分组数组元素

解决方案代码

直接使用Array.reduce方法可高效完成动态分组,代码如下:

const items = [
   { id: 1, account: 'acct_101' },
   { id: 2, account: 'acct_52' },
   { id: 3, account: 'acct_33' },
   { id: 4, account: 'acct_101' },
   { id: 5, account: 'acct_101' },
];

// 核心分组逻辑
const groupedAccounts = items.reduce((groups, item) => {
  const account = item.account;
  // 若当前账号未创建分组,初始化空数组
  if (!groups[account]) {
    groups[account] = [];
  }
  // 将当前元素加入对应分组
  groups[account].push(item);
  return groups;
}, {});

// 匹配你期望的外层数组结构
const item_groups = [groupedAccounts];

console.log(item_groups);

输出结果

执行后会得到你需要的结构:

item_groups:  [
  { 
    acct_101: [
      { id: 1, account: 'acct_101' },
      { id: 4, account: 'acct_101' },
      { id: 5, account: 'acct_101' },
    ],
    acct_52: [
      { id: 2, account: 'acct_52' },
    ],
    acct_33: [
     { id: 3, account: 'acct_33' },
    ],
  }
]

逻辑说明

  • reduce方法的核心是维护一个累积对象groups,用来存储每个账号对应的元素数组;
  • 遍历每个元素时,以item.account为键,检查该键是否存在于groups中:
    • 不存在则创建新的空数组作为该键的值;
    • 存在则直接将当前元素推入对应数组;
  • 最后将分组结果包裹进数组,完全匹配你需要的输出格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 12:45:37