[Vuejs]-How to compute an array and return a nested array of to numbers inside a parent array using vuejs/javascript?

1👍

You want this:

computed: {
    departureStops() {
        return this.stops.reduce((points, stop) => {
            const stopPoints = stop["Points"].map(point => [point.Lat, point.Lon]); // Make your array of points for this stop
            return points.concat(stopPoints); // add all of them to the final array
        }, []);
    },
},

Or:

computed: {
    departureStops() {
        return this.stops.flatMap(stop => {
            // Transform each stop into its array of points
            return stop["Points"].map(point => [point.Lat, point.Lon]);
        });// And flatten the structure to an array of points
    },
},

For instance:

const stops = [
  {
    "name": "Bob", 
    "Points": [{"Lat": 2, "Lon": 3}, {"Lat": 4, "Lon": 5} ] 
  },
  {
    "name": "John", 
    "Points": [{"Lat": 6, "Lon": 7}, {"Lat": 8, "Lon": 9} ]  
  }
];

const departureStops = stops.flatMap(stop => {
    return stop["Points"].map(point => [point.Lat, point.Lon]);
});

console.log(departureStops);

0👍

You don’t return a value in computed function, because you use forEach. If you use like:

const stops = [
      {
        'name': 'Bob',
        'Points': [{ 'Lat': 2, 'Lon': 3 }, { 'Lat': 4, 'Lon': 5 } ],
      },
      {
        'name': 'John',
        'Points': [{ 'Lat': 6, 'Lon': 7 }, { 'Lat': 8, 'Lon': 9 } ],
      },
    ]
departureStops() {
  const stop = [];
  this.test.forEach((s) => s['Points'].forEach((dp) => {
    stop.push([dp.Lat, dp.Lon]);
  }));
  return stop;
}

The result will be:

[ [ 2, 3 ], [ 4, 5 ], [ 6, 7 ], [ 8, 9 ] ]

Leave a comment