简体   繁体   中英

How to Concatenate Arrays of Objects and return single Array of Arrays?

I recieve 4 arrays from Geoserver. Each of these arrays contain objects holding lat lng data as here geoserver response . I need to merge these 4 arrays in one single Array and then convert objects inside them into arrays. This was used to structure some other response from another 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. 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. 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];
        })
    })

There is a great npm package for this kinda task that i used once called deepmerge You can use it to merge one or more arrays or objects into one and control the enumerable properties.

If you need lazy loading of values only when you access it, you can turn the accumulator function into a generator (for performance). There's other things you can do like using promises and a generator to yield values. 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. You should just map coordsArray directly.

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:

xxy = routeLayer.map( ({ _layers: { _latlngs: xy })  => Object.values(xy) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM