如何在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
相关产品推荐
相关产品推荐

