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

如何将GraphQL响应转换为可复用的指定结构数据并赋值给变量

问题解决:GraphQL响应数据格式转换

问题背景

我拿到一份GraphQL响应数据,想要将其转换为指定的对象结构并赋值给变量,方便在应用中复用。

GraphQL原始响应

{
    "data": {
        "organization": {
            "tables": {
                "edges": [
                    {
                        "node": {
                            "id": "1wer45",
                            "name": "Node One",
                            "internal_id": "12345"
                        }
                    },
                    {
                        "node": {
                            "id": "j8IrxJ425",
                            "name": "Node Two",
                            "internal_id": "54321"
                        }
                    }
                ]
            }
        }
    }
}

期望转换后的格式

{
    "Node One": { id: '1wer45', internal_id: '12345' },
    "Node Two": { id: 'j8IrxJ425', internal_id: '54321' }
}

我的错误代码

const reFormat = func((result) => {
  let test = {};
  let obj1 = {};
  let table_details = result.data.data.organization.tables.edges.map((d) => {
    obj1["id"] = d.node.id;
    obj1["internal_id"] = d.node.internal_id;
    test[d.node.name] = obj1;
    return test;
  });
  console.log(table_details);
});
reFormat({ query: tables("13456") }).then((res) => res);

问题分析

  1. 引用复用问题:循环外声明的obj1是单一对象,每次循环仅修改其属性,导致test中所有键都指向同一个对象引用,最终所有值都会被最后一次循环覆盖。
  2. 方法误用:map用于生成新数组,但我们需要的是单一对象,用map会得到包含重复对象的数组,不符合需求。
  3. 路径错误:result.data.data多了一层data,正确路径应为result.data.organization.tables.edges。
  4. 函数声明错误:func不是合法的函数定义方式,应使用function或箭头函数。

正确解决方案

方案一:使用forEach遍历构建对象

const reFormat = async (result) => {
  const formattedTables = {};
  result.data.organization.tables.edges.forEach((edge) => {
    const { id, name, internal_id } = edge.node;
    formattedTables[name] = { id, internal_id };
  });
  console.log(formattedTables);
  return formattedTables;
};

// 调用示例(假设tables()返回Promise)
reFormat(await tables("13456")).then(res => {
  // 在此处使用转换后的res变量
});

方案二:使用reduce简化代码

const reFormat = async (result) => {
  const formattedTables = result.data.organization.tables.edges.reduce((acc, edge) => {
    const { id, name, internal_id } = edge.node;
    acc[name] = { id, internal_id };
    return acc;
  }, {});
  console.log(formattedTables);
  return formattedTables;
};

// 调用示例
reFormat(await tables("13456")).then(res => {
  // 使用转换后的数据
});

关键修正点

  • 每次循环创建新对象,避免引用复用导致的覆盖问题。
  • 选择forEach或reduce构建单一对象,而非map生成数组。
  • 修正数据访问路径,移除多余的data层级。
  • 使用合法的异步函数声明,适配后续的.then调用逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 18:34:59