[英]How to Concatenate Arrays of Objects and return single Array of Arrays?
I recieve 4 arrays from Geoserver.我从 Geoserver 收到 4 arrays。 Each of these arrays contain objects holding lat lng data as here geoserver response .这些 arrays 中的每一个都包含保存 lat lng 数据的对象,如geoserver response 。 I need to merge these 4 arrays in one single Array and then convert objects inside them into arrays.我需要将这 4 个 arrays 合并到一个数组中,然后将其中的对象转换为 arrays。 This was used to structure some other response from another API:这用于构建来自另一个 API 的其他响应:
var routes = e.routes[0].coordinates
var coords = routes.map(function(obj){
return Object.keys(obj).sort().map(function(key){
return obj[key];
})
})
This is routes and this is coords and coords is expected result for Geoserver response.这是路线,这是坐标,坐标是 Geoserver 响应的预期结果。 I get my geoserver response .我得到我的地理服务器响应。 structured as shown in image after I did this:在我这样做之后,结构如图所示:
function goPark(routeLayer){
var finalRoute = routeLayer._layers;
var coordsArray = Object.keys(finalRoute).map(key => {
return finalRoute[key]
});
coordsArray.forEach(function(data){
var xy = data._latlngs;
})
If i proceed with code below I recieve arrays structured as I want, see here , but still separated.如果我继续下面的代码,我会收到 arrays 的结构,请参阅此处,但仍然分开。 I need to merge them somehow in one single array!我需要以某种方式将它们合并到一个数组中!
var xxy = xy.map(function(obj){
return Object.keys(obj).map(function(key){
return obj[key];
})
})
If you need lazy loading of values only when you access it, you can turn the accumulator function into a generator (for performance).如果仅在访问时才需要延迟加载值,则可以将累加器 function 变成生成器(用于性能)。 There's other things you can do like using promises and a generator to yield values.您还可以做其他事情,例如使用 Promise 和生成器来产生值。 Though if you aren't seeing any performance issues it's unnecessary.尽管如果您没有看到任何性能问题,则没有必要。
function accGoPark(reset) {
return accFn(goPark, reset);
}
function accFn(fn, reset) {
const accs = accFn.accs = accFn.accs || {};
const { name } = fn;
accs[name] = !accs[name] || reset ? [] : accs[name];
accs[name] = accs[name].concat( fn() );
return accs[name];
}
You are just setting a variable xy to a reference to your last data._latlngs iterated in your forEach loop, which is why you only get the last one.您只是将变量 xy 设置为对您的最后一个数据的引用。在 forEach 循环中迭代的_latlngs,这就是为什么您只得到最后一个。 You should just map coordsArray directly.您应该直接使用 map coordsArray。
xxy = coordsArray.map(function(data){
var obj = data._latlngs;
return Object.keys(obj).map(function(key){
return obj[key];
})
})
Using Object.values, destructuring, and arrow functions to simplify syntax:使用 Object.values、解构和箭头函数来简化语法:
xxy = routeLayer.map( ({ _layers: { _latlngs: xy }) => Object.values(xy) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.