【问题标题】:How do I save results of a “for” loop into a single variable? (JavaScript ) Node.js如何将“for”循环的结果保存到单个变量中? (JavaScript)Node.js
【发布时间】:2026-01-13 22:50:02
【问题描述】:

我有一个这样的数组:

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

到目前为止,我只能控制台记录结果,但我需要一些关于如何将结果保存在一个变量中的建议。

这是我得到的:

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 端点提供它。 有人知道该怎么做吗? 谢谢!

【问题讨论】:

  • 创建一个空数组并将结果推送到该数组中
  • 不要使用for循环,使用.map()方法
  • 我试过了,我没有得到正确的结果。数组的一个元素应该是一个带有两个键值对的 json 对象。
  • @Bergi - 我也试过了。由于某种原因,它没有给我正确的结果。 formatted_polygons = polygons.map(function(polygon){ return { _id : polygon._id, coordinates : polygon.geometry.coordinates } }); 结果如下所示:{ _id: '12345', coordinates: [ [Array] ] }, { _id: '67890', coordinates: [ [Array] ] }
  • 我看不到数组里面有什么。我不知道为什么

标签: javascript node.js ecmascript-6


【解决方案1】:

你可以这样做

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);

【讨论】:

    【解决方案2】:

    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);

    【讨论】:

      最近更新 更多