如何对已按id分组的JSON对象数组按name重新分组?
按account_name重新分组JSON数据的实现方法
需求背景
后端API返回的JSON响应中,remote对象下的数据按account_id(或others标识)分组,现需将这些数据重新按account_name字段分组,适配UI展示需求。
当前响应示例
{ "remote": { "12345": [ { "id": "642232324873ab98", "name": "Akon", "account_id": "12345", "account_name": "director" } ], "56780": [ { "id": "6434343a1873ab98", "name": "Jim", "account_id": "56780", "account_name": "director" } ], "others": [ { "id": "6421ca1873ab980001bd465a", "account_id": null, "account_name": "others" } ] } }
期望输出示例
{ "remote": { "director": [ { "id": "642232324873ab98", "name": "Akon", "account_id": "12345", "account_name": "director" }, { "id": "6434343a1873ab98", "name": "Jim", "account_id": "56780", "account_name": "director" } ], "others": [ { "id": "6421ca1873ab980001bd465a", "account_id": null, "account_name": "others" } ] } }
实现方法(JavaScript)
通过遍历原remote对象的子数组,将元素按account_name归类到新对象中,代码如下:
// 假设原响应数据为response const response = { "remote": { "12345": [ { "id": "642232324873ab98", "name": "Akon", "account_id": "12345", "account_name": "director" } ], "56780": [ { "id": "6434343a1873ab98", "name": "Jim", "account_id": "56780", "account_name": "director" } ], "others": [ { "id": "6421ca1873ab980001bd465a", "account_id": null, "account_name": "others" } ] } }; // 初始化分组后的remote对象 const groupedRemote = {}; // 遍历原remote下的所有数组 Object.values(response.remote).forEach(itemList => { itemList.forEach(item => { const key = item.account_name; // 若当前account_name对应的数组不存在则初始化 if (!groupedRemote[key]) { groupedRemote[key] = []; } // 将元素推入对应数组 groupedRemote[key].push(item); }); }); // 最终结果 const result = { remote: groupedRemote }; console.log(JSON.stringify(result, null, 2));
代码说明
- 用
Object.values(response.remote)获取原remote对象下的所有子数组; - 嵌套遍历每个子数组的元素,以
account_name作为新分组的键; - 检查新对象中是否存在该键对应的数组,不存在则初始化,再将元素推入对应数组;
- 最后将分组后的对象包装成目标格式。
内容的提问来源于stack exchange,提问作者sagar verma
相关产品推荐
相关产品推荐

