Search code examples
arraylistvuejs2uniquevuex

return unique values from array in vuejs


I am using Vuejs and Vuex to return an array of item objects. The items can be submitted to the database with the same name multiple times. I need to create a list of unique item names in an array in Vuejs.

from map getters below all Items returns an array of objects that looks like

[
  {"name": "item one", "number": "001", "size": "4000kb"}
  {"name": "item two", "number": "002", "size": "5000kb"}
  {"name": "item three", "number": "003", "size": "6000kb"}
]


   methods: {
    ...mapActions(["fetchItems"])
  },
  computed: {
    ...mapGetters(["allItems"]),
 itemNames: function() {
      return [...new Set(this.allItems.name)]
    } 
  },
  created() {
    this.fetchItems(),
    this.itemNames()
  },

In computed properties itemNames if I take off the .name [..new Set(this.allItems)] the array returns the complete objects - how can I just pull the name out to a list?

The v-for does not return the array

<v-list-item v-for="(itemName, index ) in itemNames" :key="index">
  <v-list-item-content> {{ itemName }}</v-list-item-content>
</v-list-item>

Thanks for any help.


Solution

  • I solved this one in computed properties by mapping the items to a new array like so

     itemNames: function() {
          return  [...new Set(this.allItems.map(x => x.item.Name))]
        }