[Vuejs]-Trying to prepend route parent URLs in Javascript with reduce

1👍

The third parameter of the reduce callback is the index, so you can’t use that to pass in the parent path. What I’d suggest is converting that method into a recursive function. I’ve prepared an example based on your code:

(note: I’ve changed the way you set ‘outputRouteDetails’ to use the Vue setter method, this will ensure that this property remains reactive and that the template will update when its values change)

  methods: {
    getAllRoutesDetails() {
      this.$set(this.$data, 'outputRouteDetails', this.reduceRoutes(this.originalObject));

      console.log(this.outputRouteDetails);
    },

    reduceRoutes (obj, parentPath) {
      return obj.reduce((acc, route) => {
        acc.push(this.getRoute(route, parentPath));

        if (route.children && route.children.length > 0) {
          parentPath = parentPath ? parentPath+route.path : route.path;
          const children = this.reduceRoutes(route.children, parentPath);
          acc.push(...children);
        }

        return acc;
      }, []);
    },

    getRoute (route, parentPath) {
      const fullPath = parentPath ? `${parentPath}${route.path}` : route.path;

      return {
        path: fullPath,
        name: route.name,
        component: typeof route.component === 'function' ? route.component.name : route.component,
        meta: route.meta,
      };
    }
  }

Fiddle link: https://jsfiddle.net/JordanRanson/p0dqLay4/20/

Leave a comment