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

如何在GraphQL中绕过嵌套的data与attributes对象?

问题:如何绕过GraphQL返回结果中的data和attributes嵌套?

现有GraphQL片段:

fragment PropertyInformationStateFragment on Property{
    property_state{
      data{
        attributes{
          state
          description
        }
      }
    }
}

当前返回数据示例:

"property_state": {
  "data": {
    "attributes": {
      "state": "Tres bon état",
      "description": "Tres bon état du bien immobilier"
    }
  }
}

期望得到的返回数据格式:

"property_state": {
  "state": "blabla",
  "description": "blabla"
}

解决方案

分两种场景处理:

1. 有权修改GraphQL服务端(推荐方案)

如果能控制GraphQL服务端的Schema或Resolver逻辑,直接调整Property类型下property_state字段的返回结构:

  • 修改对应Resolver函数,让它直接返回attributes层级的内容,不再嵌套data和attributes
  • 前端查询片段可以简化为:
fragment PropertyInformationStateFragment on Property{
    property_state{
      state
      description
    }
}

2. 仅能在前端处理返回数据

如果无法修改服务端,就在前端拿到数据后做一层结构转换:

JavaScript 基础转换示例

// 假设原始接口返回数据为responseData
const transformedData = {
  ...responseData,
  property_state: responseData.property_state.data.attributes
};

通用嵌套字段扁平化函数

如果有多个类似嵌套结构需要处理,可以封装工具函数批量处理:

function flattenNested(obj, nestedPath) {
  const paths = nestedPath.split('.');
  let result = obj;
  for (const path of paths) {
    result = result?.[path] || {};
  }
  return result;
}

// 使用示例
const simplifiedPropertyState = flattenNested(responseData.property_state, 'data.attributes');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 22:27:20