如何解构嵌套GeoJSON对象以获取指定格式的数组?
实现方案
你可以通过数组遍历+对象/数组解构的方式快速完成格式转换,具体实现如下:
1. 解构实现(推荐)
直接在map遍历的回调参数中完成字段解构,代码简洁易读:
// 你的原始GeoJSON对象 const originData = {"type":"FeatureCollection","name":"zentroide_bezirke_4326","crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:OGC:1.3:CRS84"}},"features":[{"type":"Feature","properties":{"fid":2,"id":"BEZIRKSGRENZEOGD.10890","NAMEK":"Josefstadt","BEZNR":8,"BEZ_RZ":"VIII","NAMEK_NUM":"8., Josefstadt","NAMEK_RZ":"VIII. Josefstadt","NAMEG":"JOSEFSTADT","LABEL":"VIII.","BEZ":"08","DISTRICT_CODE":1080,"STATAUSTRIA_BEZ_CODE":908,"STATAUSTRIA_GEM_CODE":90801,"FLAECHE":1089945.694,"UMFANG":4170.3,"AKT_TIMESTAMP":"2021-09-13","SE_SDO_ROWID":10890,"SE_ANNO_CAD_DATA":null},"geometry":{"type":"Point","coordinates":[16.347822689187193,48.211029313540855]}},{"type":"Feature","properties":{"fid":3,"id":"BEZIRKSGRENZEOGD.10891","NAMEK":"Innere Stadt","BEZNR":1,"BEZ_RZ":"I","NAMEK_NUM":"1., Innere Stadt","NAMEK_RZ":"I. Innere Stadt","NAMEG":"INNERE STADT","LABEL":"I.","BEZ":"01","DISTRICT_CODE":1010,"STATAUSTRIA_BEZ_CODE":901,"STATAUSTRIA_GEM_CODE":90101,"FLAECHE":2868773.8207,"UMFANG":6972.75,"AKT_TIMESTAMP":"2021-09-13","SE_SDO_ROWID":10891,"SE_ANNO_CAD_DATA":null},"geometry":{"type":"Point","coordinates":[16.36939878396175,48.208360983479615]}}]} const data = originData.features.map(({ properties: { NAMEK }, geometry: { coordinates: [lng, lat] } }) => ({ NAMEK, coordinates: { lat, lng } }))
注意:GeoJSON规范中坐标数组顺序为
[经度, 纬度],所以提取时lat对应数组索引1的取值,lng对应索引0的取值,不要写反导致坐标偏移。
2. 普通取值实现
如果对解构语法不熟悉,也可以用常规的链式取值实现,逻辑更直观:
const data = originData.features.map(feature => { return { NAMEK: feature.properties.NAMEK, coordinates: { lat: feature.geometry.coordinates[1], lng: feature.geometry.coordinates[0] } } })
两种方式性能差异可以忽略,解构写法的优势是减少重复的前缀代码,提取字段越多优势越明显。
内容的提问来源于stack exchange,提问作者Lenn
相关产品推荐
相关产品推荐

