You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按反斜杠分割数组字符串并提取所需坐标数据

Gatsby项目处理WordPress返回的坐标数据解决方案

现有代码问题说明

  • map方法不会修改原数组,只会返回新数组,你之前的两次polygonareas.map(...)都没有接收返回值,处理结果直接丢失
  • Array.shift()的返回值是被删除的首元素,你直接把这个返回值赋值给coordinates,会导致坐标直接变成字符串,而非剩下的数组
  • 你拿到的coordinates字段本身就是标准JSON序列化后的数组字符串,不需要手动按|、反斜杠分割,直接JSON.parse解析后处理更简单,不会出现转义字符处理的问题

最优解决方案

直接解析JSON格式的坐标字符串,不需要处理转义字符:

const polygonareas = data.allWpArea.nodes.map(area => {
  // 第一步:把坐标字符串转成真实数组,自动处理转义符、引号
  const coordStrArray = JSON.parse(area.geometry.coordinates)
  // 第二步:处理每个坐标项,按|分割取后半段,再转成数字数组符合GeoJSON规范
  const coordinates = coordStrArray.map(item => {
    const coordStr = item.split('|')[1]
    return coordStr.split(',').map(Number)
  })
  return {
    geometry: {
      type: "Polygon",
      // 注意GeoJSON的Polygon要求是嵌套数组,这里需要额外包一层[]
      coordinates: [coordinates]
    },
    properties: {
      title: area.properties.title,
      slug: area.properties.slug
    }
  }
})

处理后得到的结构完全符合GeoJSON规范,示例如下:

{
  "geometry": {
    "type": "Polygon",
    "coordinates": [
      [
        [55.852081917669, 11.704305226785],
        [55.851551628025, 11.706345689048],
        ...其余坐标
      ]
    ]
  },
  "properties": {
    "title": "Area 1",
    "slug": "area-1"
  }
}

兼容原有手动分割逻辑的备选方案

如果你坚持要按原有分割逻辑处理,可以直接提取引号前的坐标部分:

const polygonareas = data.allWpArea.nodes.map(area => ({
  geometry: {
    type: "Polygon",
    coordinates: [area.geometry.coordinates
      .split('|')
      // 跳过第一个元素,代替shift操作
      .slice(1)
      .map(coord => {
        // 直接取引号前的坐标部分,不需要处理反斜杠
        const coordStr = coord.split('"')[0]
        return coordStr.split(',').map(Number)
      })]
  },
  properties: {
    title: area.properties.title,
    slug: area.properties.slug
  }
}))

内容的提问来源于stack exchange,提问作者Dougless

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 00:18:03