是否应该使用.map()从HttpClient请求中重组数据?

时间:2018-07-26 19:54:11

标签: angular geojson

我的数据来自我的剩余api

{[{"location":1,"latitude":"00.000","longitude":"000.000"}, 
  {"location":2,"latitude":"00.000","longitude":"000.000"}]}

但是我想以

的形式提供
{"type":"FeatureCollection",
"features":[
    {"type":"Feature",
    "geometry":{
        "type":"Point",
        "coordinates":[00.0000,00.00000]
                },
    "properties":{
        "location":1
                  }
  },
   {"type":"Feature",
    "geometry":{
        "type":"Point",
        "coordinates":[00.00000,-00.0000]
                },
    "properties":{
        "location":2
                  }
]}

所以我需要添加类型:featurecollection和features:[] 在我甚至开始遍历对象之前……

然后,我需要添加几何和属性对象。我可以先在模型中完成所有这些工作吗?

我什至不知道从哪里开始。任何指导将不胜感激。

2 个答案:

答案 0 :(得分:0)

我认为实际数据只是数组,您发布的内容无效。

您可以简单地将数组映射到所需的输出,如下所示

const arr = [{
    "location": 1,
    "latitude": "00.000",
    "longitude": "000.000"
  },
  {
    "location": 2,
    "latitude": "00.000",
    "longitude": "000.000"
  }
];

const res = {
  type: 'Feature Collection',
  features: arr.map(e => ({
    "type": "Feature",
    "geometry": {
      "type": "Point",
      "coordinates": [e.latitude, e.longitude]
    },
    "properties": {
      "location": e.location
    }
  }))
};

console.log(res);

答案 1 :(得分:0)

您可以执行以下操作:

const features = data.map(value => {
    const { location, latitude, longitude } = value;
    return {
        type: "Feature",
        geometry: {
            type: "Point",
            coordinates: [ latitude, longitude ],
            properties: {
                location
            }
        }
    }
});

const obj = { type: "FeatureCollection", features };
console.log(obj);