0

I do currently map through GraphQL data like so:

  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()
          ]
        ]
      }
    }
  )) 

The GraphQL query I use looks like this:

query {
  allWordpressWpPlots {
    edges {
      node {
        coordinates {
          coord
        }
      }
    }
  }
}

..and the output from GraphiQL looks like this:

{
  "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"
              }
            ]
          }
        }
      ]
    }
  }
}

The map function do return an object in the correct format, but my problem is that the "coordinates" node from GrapQL comes in different lengths. I want to loop through the node using a foreach-loop based on the length of the array, but I get a syntax error when I try to javascript within the map function.

How can I build a "coordinates" array with X amount of object elements from GraphQL?

1 Answer 1

1

You can nest map calls. Not quite sure why coordinates is an array inside another array, but keeping that as is:

const plotDataArray = data.allWordpressWpPlots.edges.map(plot => ({
  geometry: {
    type: plot.node.properties.geotype,
    coordinates: [
      plot.node.coordinates.map(coordinate => {
        return coordinate.coord.split(",").reverse()
      }),
    ]
  },
}))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.