首页 > 解决方案 > 单独的数组并将其分配给角度中的不同参数

问题描述

我有一个数组,我在其中发送多边形的坐标。每个多边形仅包含 4 个点。如下图所示

{
  "Coordinates": {
    "Polygon": [
      [[30,75],[43,71],[48,95],[23,107]],
      [[76,53],[169,52],[147,89],[83,108]],
      [[30,75],[43,71],[48,95],[23,107]],
      [[76,53],[169,52],[147,89],[83,108]],
      [[178,67],[203,75],[194,134],[154,134]]
    ]
  }
}

我想分离出这些多边形,如下所示。我怎样才能动态获得它?

{
  "Coordinates": {
    "Polygon": [[30,75],[43,71],[48,95],[23,107]],
    "Polygon1": [[76,53],[169,52],[147,89],[83,108]],
    "Polygon2": [[30,75],[43,71],[48,95],[23,107]],
    "Polygon3": [[178,67],[203,75],[194,134],[154,134]]
  }
}

标签: javascriptangular

解决方案


您可以通过以下方式获得所需的结构:

const object = {
  "Coordinates": {
    "Polygon": [
      [[ 30, 75],[ 43, 71],[ 48, 95],[ 23,107]],
      [[ 76, 53],[169, 52],[147, 89],[ 83,108]],
      [[ 30, 75],[ 43, 71],[ 48, 95],[ 23,107]],
      [[ 76, 53],[169, 52],[147, 89],[ 83,108]],
      [[178, 67],[203, 75],[194,134],[154,134]]
    ]
  }
};

// In the line below `...object` is optional if `object` only
// contains the key `Coordinates` and no other keys.
const result = { ...object, Coordinates: {} };
object.Coordinates.Polygon.forEach((coords, i) => {
  result.Coordinates[`Polygon${i}`] = coords;
});

console.log(result);

但是我真的不明白你想在这里实现什么。这种结构上的变化将对单个“多边形”的访问从 更改object.Coordinates.Polygon[0]result.Coordinates.Polygon0

由于多边形的集合不再是数组而是对象,因此您也无法使用数组方法map,例如filter等,这些方法都非常有用。


推荐阅读