[Vuejs]-Dealing with linked lists in Vue

0👍

Edited

Transform you data into an iterable (for this case in an array), by using Object.keys() and Object.values() iterate into your Object to create the new array to display.

0👍

As @destoryer suggested, you can create a computed property that will call a another function for transforming your linked lists into an array.

computed: {
  lists() {
    // assuming that linkedLists is in your data property

    // declared under `methods` in this example
    return this.flattenLists(this.linkedLists); 
  }
},
methods: {
  flattenLists({ title, next }) {
    return next ? [title].concat(this.flattenLists(next)) : [title];
  }
}

flattenLists is a recursive function wherein if next is an object, it will call itself with next as param and concatenate the result to the current array.

In this example, it’s under methods but it would be better to put it
as a helper/util especially if you want to reuse it
in other components.

You can then use it in your v-for as such.

<ul v-for="(item, index) in lists" :key="index">
  <li>{{ item }}</li>
</ul>

Leave a comment