我正在使用nodeJs和postgres来查看网站上的一些线条。
该查询返回一个geojson returns集合。在服务器端,我使用json_build_object
创建一个GeoJSON特性集合。
const a = parseInt(request.params.start)
const b = parseInt(request.params.end)
const sql = "SELECT jsonb_build_object("+
"'type', 'FeatureCollection',"+
"'features', jsonb_agg(features.feature)"+
")"+
"FROM (" +
"SELECT json_build_object("+
"'type', 'Feature'," +
"'id', gid,"+
"'geometry', ST_AsGeoJSON(the_geom)::json,"+
"'properties', json_build_object(" +
"'cost_s', cost_s::double precision,"+
"'length_m', length_m::double precision"+
")" +
") AS feature FROM _a_route(" + a + "," + b + ")) features;"
pool.query(sql, (error, results) => {
if (error) {
throw error
}
response.send(results.rows)
})
}
然而,实际结果如下所示:
[{"jsonb_build_object":{"type":"FeatureCollection","features":[{"id":700878,"type":"Feature","geometry":{"type":"LineString","coordinates":[[8.4896534,49.9798051],[8.4867778,49.9790802],[8.4864496,49.9790044]]},"properties":{"cost_s":88.7259786788723,"length_m":246.461051885756}},{"id":686885,"type":"Feature","geometry":{"type":"LineString","coordinates":[[8.490777,49.9800852],[8.4906598,49.9800531],[8.49052,49.9800168],[8.4903212,49.9799755],[8.4896534,49.9798051]]},"properties":{"cost_s":31.1167335538295,"length_m":86.4353709828597}}.....]}}]
问题出在{"jsonb_build_object":
上。我怎么才能摆脱它呢?
发布于 2019-05-22 06:15:00
看起来您正在尝试变换对象数组的形状。您可以使用Array.prototype.map来实现此目的:
const results = {rows: [{"jsonb_build_object":{"type":"FeatureCollection","features":[{"id":700878,"type":"Feature","geometry":{"type":"LineString","coordinates":[[8.4896534,49.9798051],[8.4867778,49.9790802],[8.4864496,49.9790044]]},"properties":{"cost_s":88.7259786788723,"length_m":246.461051885756}},{"id":686885,"type":"Feature","geometry":{"type":"LineString","coordinates":[[8.490777,49.9800852],[8.4906598,49.9800531],[8.49052,49.9800168],[8.4903212,49.9799755],[8.4896534,49.9798051]]},"properties":{"cost_s":31.1167335538295,"length_m":86.4353709828597}}]}}]}
const changedShape = results.rows.map(row => row.jsonb_build_object)
console.log(changedShape)
https://stackoverflow.com/questions/56246633
复制相似问题