我目前确实通过 GraphQL 数据进行映射,如下所示:
const plotDataArray = data.allWordpressWpPlots.edges.map(plot => (
{
geometry: {
type: plot.node.properties.geotype,
coordinates: [
[
plot.node.coordinates[0].coord.split(",").reverse(),
plot.node.coordinates[1].coord.split(",").reverse(),
plot.node.coordinates[2].coord.split(",").reverse(),
plot.node.coordinates[3].coord.split(",").reverse(),
plot.node.coordinates[4].coord.split(",").reverse()
]
]
}
}
))
我使用的 GraphQL 查询如下所示:
query {
allWordpressWpPlots {
edges {
node {
coordinates {
coord
}
}
}
}
}
..GraphiQL 的输出如下所示:
{
"data": {
"allWordpressWpPlots": {
"edges": [
{
"node": {
"coordinates": [
{
"coord": "56.064655444812,9.6949704566207"
},
{
"coord": "56.064575958599,9.6994982706574"
},
{
"coord": "56.06046088577,9.6994719476694 "
},
{
"coord": "56.060440367157,9.6951515896261"
},
{
"coord": "56.064655444812,9.6949704566207"
}
]
}
}
]
}
}
}
map 函数确实以正确的格式返回一个对象,但我的问题是 GrapQL 中的“坐标”节点的长度不同。我想使用基于数组长度的 foreach 循环来遍历节点,但是当我尝试在映射函数中使用 javascript 时,出现语法错误。
如何从 GraphQL 构建一个包含 X 个对象元素的“坐标”数组?
最佳答案
您可以嵌套map
调用。不太确定为什么坐标是另一个数组中的数组,但保持原样:
const plotDataArray = data.allWordpressWpPlots.edges.map(plot => ({
geometry: {
type: plot.node.properties.geotype,
coordinates: [
plot.node.coordinates.map(coordinate => {
return coordinate.coord.split(",").reverse()
}),
]
},
}))
关于javascript - 如何将 GraphQL 中的对象元素推送到 javascript 对象中的嵌套数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60606960/