我应该使用 .map() 从 HttpClient 请求中重组我的数据吗?
Should I use .map() to restructure my data from an HttpClient request?
我的数据来自我的休息 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 和功能:[]
在我什至开始遍历对象之前...
然后我需要添加几何和属性对象。我可以先在模型中完成所有这些吗?
我真的不知道从哪里开始。任何指导将不胜感激。
我假设真正的数据只是数组,您发布的内容无效。
您可以简单地将数组映射到所需的输出,如下所示
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);
您可以这样做:
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);
我的数据来自我的休息 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 和功能:[] 在我什至开始遍历对象之前...
然后我需要添加几何和属性对象。我可以先在模型中完成所有这些吗?
我真的不知道从哪里开始。任何指导将不胜感激。
我假设真正的数据只是数组,您发布的内容无效。
您可以简单地将数组映射到所需的输出,如下所示
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);
您可以这样做:
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);