【发布时间】:2022-12-06 06:49:50
【问题描述】:
我有一个 GraphQL 端点,它以以下格式返回数据(称为位置);
[
{
"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"
}
]
},
]
我已经尝试过使用 array.map 方法来执行以下操作;
const locations = locations.map((location) =>
location.services.nodes.map((service) => service)
);
【问题讨论】:
-
你不能让你的端点以正确的结构返回数据吗?
标签: javascript arrays