[Vuejs]-Vuetify TreeView Data Manipulation

1👍

It seems that you want to rearrange those items to be displayed as a tree view.

As you’ve posted, each of then are displayed as objects in a flat array, like the following:

[
  { id: 1, name: "hot-dog",
    children: [ { name: "meat" } ] },
  { id: 2, name: "meat",
    children: [ { name: "salt" }, { name: "horse-meat" } ] },
  { id: 3, name: "salt" },
  { id: 4, name: "horse-meat" },
];

And need to be transformed into a array of master objects.

I’ve written a MRE that can display it working. Also, see this working example on codepen.

<div id="app">
  <v-app id="inspire">
    <v-treeview :items="formattedItems"></v-treeview>
  </v-app>
</div>
new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data: () => ({
    items: [
      {
        id: 1,
        name: "hot-dog",
        children: [
          {name:"meat"},
        ],
      },
      {
        id: 2,
        name: "meat",
        children: [
          {name:"salt"},
          {name:"horse-meat"},
        ],
      },
      {
        id: 3,
        name: "pancake",
        children: [
          {name: "honey"},
        ]
      },
      {
        id: 4,
        name: "honey",
      },
      {
        id: 5,
        name: "salt",
      },
      {
        id: 6,
        name: "horse-meat",
      },
    ]
  }),
  computed: {
    formattedItems() {
      const mapper = function (current) {
        let child = this.find(item => item.name === current.name);
        if (child.children) {
          child.children = child.children.map(mapper, this); 
        }
        return child;
      };
      const reducer = (accum, current, index, array) => {
        if (!array.find(item => !!item.children && item.children.find(child => child.name === current.name))) {
          current.children = current.children.map(mapper, array);
          accum.push(current);
        }
        return accum;
      };
      return this.items.reduce(reducer, []);
    }
  }
})

Leave a comment