我正在从geojson文件中获取数据,我想展平数组中的数组以能够在材料表中显示此数据。
我有以下代码:
const geoListData: Array<any> = [];
const features = geoData.features; // feature array
const latIdx = 0;
const lonIdx = 1;
// iterate over each feature
features.forEach((feature: any) => {
const geoListArray: any = [];
// build up GeoListEntry
const geoListEntry: GeoListEntry = {
name: feature.properties.name,
category: feature.properties.category,
lat: feature.geometry.coordinates[latIdx],
lon: feature.geometry.coordinates[lonIdx],
prio: feature.properties.prio
};
geoListArray.push(geoListEntry);
// get values from geojson
feature.properties.values.forEach((element: any) => {
const valuesEntry: any = {
[element.name]: element.value
};
geoListArray.push(valuesEntry);
});
this.logger.debug(`geoListArray: ${JSON.stringify(geoListArray)}`);
geoListData.push(geoListArray);
});
return geoListData;
}));
我的记录器输出如下:
[{"name":"90","category":"Arc 12 month","lat":7.613333333,"lon":47.555555,"prio":0},{"bearing":12345},{"intensity_mean":0},{"intensity_min":0},{"intensity_max":0}]
但是我想要这样的东西:
[{"name":"90","category":"Arc 12 month","lat":7.613333333,"lon":47.555555,"prio":0,"bearing":12345,"intensity_mean":0,"intensity_min":0,"intensity_max":0}]
我已经接近了,但是我找不到解决方法。
你有什么主意吗?
答案 0 :(得分:3)
与其将属性推送到array
,而是直接将属性添加到object
// iterate over each feature
features.forEach((feature: any) => {
const geoListArray: any = [];
// build up GeoListEntry
const geoListEntry: GeoListEntry = {
name: feature.properties.name,
category: feature.properties.category,
lat: feature.geometry.coordinates[latIdx],
lon: feature.geometry.coordinates[lonIdx],
prio: feature.properties.prio
};
// get values from geojson
feature.properties.values.forEach((element: any) => {
geoListEntry[element.name] = element.value
});
geoListArray.push(geoListEntry);
this.logger.debug(`geoListArray: ${JSON.stringify(geoListArray)}`);
geoListData.push(geoListArray);
});
答案 1 :(得分:-1)
从技术上讲,它不是数组的数组,而是要合并的对象的集合:
const data = [
{ id: 1 },
{ lat: 10 },
{ lng: 20 },
];
console.log(data.reduce((p, n) => ({...p, ...n}), {}));
只要您真的想要展平功能,就可以了:
const data = [
[{ id: 1 }],
[{ lat: 10 }],
[{ lng: 20 }],
];
console.log(Array.prototype.concat.apply([], data));
将两者混在一起?
const data = [
[{ id: 1 }],
[{ lat: 10 }],
[{ lng: 20 }],
];
console.log((Array.prototype.concat.apply([], data)).reduce((p, n) => ({...p, ...n}), {}));