如何根据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);
你的代码存在的问题
- 仅通过
element[index+1]对比当前元素与下一个元素,无法收集所有同test_id的元素(比如第三个test_id=123的元素会被遗漏) - 未处理分组后的格式转换逻辑,也没考虑单个
role的展示需求 - 误用
map方法:map用于逐个转换元素,不适合做分组聚合操作
内容的提问来源于stack exchange,提问作者rasif sahl
相关产品推荐
相关产品推荐

