我有一个像这样的数组:
var polygons = [
{
"_id" : "12345",
"geometry" : {
"coordinates" : [[
[9.123553, 48.71568],
[ 9.119548, 48.71526 ]
]]
}
},
{
"_id" : "67890",
"geometry" : {
"coordinates" : [[
[ 9.090445, 48.715736 ],
[ 9.089583, 48.715687 ]
]]
}
}
]
我需要在一个变量中输入以下结果:
[
{
"_id" : "12345",
"coordinates" : [[
[9.123553, 48.71568],
[ 9.119548, 48.71526 ]
]]
},
{
"_id" : "67890",
"coordinates" : [[
[ 9.090445, 48.715736 ],
[ 9.089583, 48.715687 ]
]]
}
]
到目前为止,我只能console.log结果,但是我需要一些有关如何将结果保存到一个变量中的建议。
这就是我得到的:
function printPolygons() {
for (var i = 0; i < polygons.length; i++) {
console.log('"polygon_id" : ' + JSON.stringify(polygons[i]._id, null, 4) + ",");
console.log('"coordinates" : '+ JSON.stringify(polygons[i].geometry.coordinates, null, 4));
};
};
输出在控制台中看起来不错,但是我需要为REST API端点提供它。 有人知道怎么做吗? 谢谢!
答案 0 :(得分:0)
您可以这样做
const polygons = [
{
"_id" : "12345",
"geometry" : {
"coordinates" : [[
[9.123553, 48.71568],
[ 9.119548, 48.71526 ]
]]
}
},
{
"_id" : "67890",
"geometry" : {
"coordinates" : [[
[ 9.090445, 48.715736 ],
[ 9.089583, 48.715687 ]
]]
}
}
];
const result = polygons.map(({ _id, geometry }) => {
return {
_id,
coordinates: geometry.coordinates
};
});
console.log(result);
答案 1 :(得分:0)
var polygons = [{
"_id": "12345",
"geometry": {
"coordinates": [
[
[9.123553, 48.71568],
[9.119548, 48.71526]
]
]
}
},
{
"_id": "67890",
"geometry": {
"coordinates": [
[
[9.090445, 48.715736],
[9.089583, 48.715687]
]
]
}
}
]
polygons = polygons.map(({
_id,
geometry
}) => ({
_id,
coordinates: geometry
}));
console.log(polygons);