Home > Back-end >  Creating unique list from vue object on page load (computed)
Creating unique list from vue object on page load (computed)

Time:10-07

In my vue, I have a data object like this:

    data:{

        items: [
                {  
                    employee: "John",
                    store: "1"
                   
                },
                {  
                    employee: "John",
                    store: "2"
                    
                },
                {  
                    employee: "Adam",
                    store: "1"
                    
                },
                {  
                    employee: "Sue",
                    store: "2"
                   
                },
                {  
                    employee: "Kelly",
                    store: "3"
                   
                }
        ]
    }

But I'm wanting to essentially loop through that by store and find any distinct store number (no matter how many times it's repeated) and build a list in another object with each unique store number. So in the example above, I have 3 distinct stores (1,2, and 3) so my new object would be expected to only have three indeces even though stores 1 and 2 were repeated above. I would expect that to look something like this:

    storesOptions: [
        {id: 1, name:"store 1"},
        {id: 2, name:"store 2"},
        {id: 3, name:"store 3"},
    ]

I've attempted with this, which I can console.log but I"m unsure of how to use it to create the object I want:

getUniqueZones() {
  return items.map(x => x.store).filter((v,i,s) => s.indexOf(v) === i)
},

How can I use this computed function to create the object I want on page load?

CodePudding user response:

You can use Set data structure which return unique element of an array:

getUniqueZones() {
  return [...new Set(items.map(item => item.store))].map((item, index) => ({ id: index, name: `store ${item}`}))
},
  • Related