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

如何根据test_id合并数组元素,生成指定格式的新数组?

合并相同test_id的role字段解决方案

核心思路

先按test_id对所有元素分组,收集每个test_id对应的所有role值,再将分组结果转换为目标格式:单个role用字符串,多个role用数组。

实现代码

const input = {"roles": [{"role": "manager","test_id": "123"},{"role": "cashier","test_id": "123"},{"role": "customer","test_id": "123"},{"role": "cashier_2","test_id": "500"}]};

// 步骤1:按test_id分组收集role
const groupedRoles = input.roles.reduce((acc, current) => {
  const { test_id, role } = current;
  if (!acc[test_id]) {
    acc[test_id] = [];
  }
  acc[test_id].push(role);
  return acc;
}, {});

// 步骤2:转换为目标格式
const output = {
  roles: Object.entries(groupedRoles).map(([test_id, roles]) => ({
    test_id,
    role: roles.length === 1 ? roles[0] : roles
  }))
};

console.log(output);

你的代码存在的问题

  1. 仅通过element[index+1]对比当前元素与下一个元素,无法收集所有同test_id的元素(比如第三个test_id=123的元素会被遗漏)
  2. 未处理分组后的格式转换逻辑,也没考虑单个role的展示需求
  3. 误用map方法:map用于逐个转换元素,不适合做分组聚合操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 06:18:27