遍历Node.js中的多维数组

时间:2018-09-26 19:11:57

标签: javascript node.js multidimensional-array ecmascript-6

嘿,我在polygons.js中得到了这个对象:

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

有人知道如何解决吗? 非常感谢您!

3 个答案:

答案 0 :(得分:1)

您可以映射数组并进行所需的更改

formatted_polygons = polygons.map(function(polygon){
    return {
        coordinates : polygon.geometry.coordinates,
        _id : polygon._id
    }
});

答案 1 :(得分:0)

似乎您只是想摆脱“几何”道具而直接获得“坐标”?

polygons.map(polygon => ({ _id: polygon._id, coordinates: polygon.geometry.coordinates }))

应该实现您想要的

答案 2 :(得分:0)

您可以简单地使用Array.map()

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 ] ]] } } ];

let result = polygons.map(({_id,geometry})=>Object.assign({},{_id, coordinates :geometry.coordinates}));
console.log(result);