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

React中如何将接口返回的map结果转换为按entity分组的指定格式

解决方案

你只需在现有接口的handler中对原始返回数据做按entity字段的分组聚合处理即可,修改后的完整代码如下:

getPackIntegrations: {
  rest: "GET /:id/integrations",
  resource: {
    name: "/packs/${id}",
    scope: "webmessenger-integrations:get",
  },
  cache: false,
  handler: async function (ctx) {
    const res = await ctx.call("packs.get", {
      id: ctx.params.id,
      fields: "integrations",
      query: {
        ...ctx.params.query,
      },
    });
    // 新增分组聚合逻辑
    const originIntegrations = res.integrations || [];
    const groupedResult = originIntegrations.reduce((acc, curr) => {
      if (!acc[curr.entity]) {
        acc[curr.entity] = {
          entity: curr.entity,
          integrations: []
        };
      }
      acc[curr.entity].integrations.push(curr.integration);
      return acc;
    }, {});
    // 转换为目标数组格式返回
    return Object.values(groupedResult);
  },
},

处理逻辑说明:

  • 先获取packs.get接口返回的原始integrations数组
  • 通过reduce方法遍历数组,按entity值做分组,将同组的integration值存入对应数组
  • 最后将分组后的对象转换为你需要的数组格式返回即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 13:06:04