如何将GraphQL返回的含nodes嵌套的locations数据扁平化?
如何扁平化GraphQL返回的locations数据结构?
原始数据结构
[ { "name": "Location 1", "description": "-", "state": "Georgia", "address": "Kennesaw, GA 30144", "services": { "nodes": [ { "id": "cG9zdDo0OQ==", "name": "Window Cleaning", "color": "#00A7E3" } ] } }, { "name": "Location 2", "description": "-", "state": "California", "address": "Los Angeles, 90016", "services": { "nodes": [ { "id": "cG9zdDo1Mg==", "name": "Large Project Waterproofing", "color": "#00668A" }, { "id": "cG9zdDo1MA==", "name": "Surfaces, Stone & Metal Refinishing", "color": "#333333" }, { "id": "cG9zdDo0OQ==", "name": "Window Cleaning", "color": "#00A7E3" } ] } } ]
预期扁平化结构
[ { "name": "Location 1", "description": "-", "state": "Georgia", "address": "Kennesaw, GA 30144", "services": [ { "id": "cG9zdDo0OQ==", "name": "Window Cleaning", "color": "#00A7E3" } ] }, { "name": "Location 2", "description": "-", "state": "California", "address": "Los Angeles, 90016", "services": [ { "id": "cG9zdDo1Mg==", "name": "Large Project Waterproofing", "color": "#00668A" }, { "id": "cG9zdDo1MA==", "name": "Surfaces, Stone & Metal Refinishing", "color": "#333333" }, { "id": "cG9zdDo0OQ==", "name": "Window Cleaning", "color": "#00A7E3" } ] } ]
原有代码的问题
你提供的代码存在两个核心问题:
- 嵌套的
map会将每个location对象直接替换为services.nodes数组,丢失了name、address等所有其他字段 - 用
const locations = locations.map(...)会重复声明同名变量,导致语法错误或变量覆盖
正确实现方式
我们需要遍历每个location对象,保留其所有原有属性,仅将services字段替换为原services.nodes数组。有两种简洁的实现方式:
方式一:展开运算符复制属性
// 注意使用不同变量名避免覆盖原始数据 const flattenedLocations = originalLocations.map(location => { return { ...location, // 复制当前location的所有属性 services: location.services.nodes // 替换services字段为nodes数组 }; });
方式二:对象解构简化代码
const flattenedLocations = originalLocations.map(({ services, ...rest }) => ({ ...rest, // 保留除services外的所有属性 services: services.nodes // 重新赋值services为nodes数组 }));
关键逻辑说明
- 使用
Array.map遍历原始数组,对每个location对象进行转换 - 通过展开运算符(
...)或解构语法保留原对象的所有其他字段 - 将
services字段的值替换为原services.nodes数组,完成扁平化
内容的提问来源于stack exchange,提问作者ryanholder
相关产品推荐
相关产品推荐

