skip to Main Content

My problem is computing an array and return a nested object array of to numbers inside using vuejs/javascript? I’m doing it via compute prop with vue js 2.
The array i’m initialy looping looks like this:

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

So Im trying to return smth like [{2, 3}, {4, 5}, {6, 7}, {8, 9}]

I’m trying to make it like this but it fails:

computed: {
    departureStops() {
      return this.stops.forEach((s) =>
        s["points"].forEach((dp) => {
          dp.Lat;
          console.log("dp.Lat", dp.Lat);
        })
      );
    },
  },

I’m expecting to return a nested object array of to numbers inside like

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

2

Answers


  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);
    Login or Signup to reply.
  2. 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() {
       return this.stops.map((s) =>
         s['Points'].map((dp) => {
           return dp.Lat;
         }),
      );
    }
    

    The result will be:

    [ [ 2, 4 ], [ 6, 8 ] ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search