arraysvue.jsobjectvuetify.jsv-select

Create array of objects for a select based on items from a data table


So I have a data table in Vuetify that's containing eventlog items. For example, it looks like this:

[{
        "id": 1,
        "actionBy": "John",
        "eventAction": "CREATED",
        "Description": ""
        "actionDate": "2022-09-02T10:31:57.223765"
    }, {
        "id": 2,
        "actionBy": "Anna",
        "eventAction": "MODIFIED",
        "Description": ""
        "actionDate": "2022-09-07T13:44:29.892831"
    }, {
        "id": 3,
        "actionBy": "Eric",
        "eventAction": "REMOVE_IMAGE",
        "Description": "Test description"
        "actionDate": "2022-09-07T13:44:39.800381"
    }, {
        "id": 4,
        "actionBy": "Sysadmin",
        "eventAction": "REMOVE_IMAGE",
        "Description": "Test description"
        "actionDate": "2022-09-08T09:21:29.272312"
    }, {
        "id": 5,
        "actionBy": "Sysadmin",
        "eventAction": "MODIFIED",
        "Description": "Test description"       
        "actionDate": "2022-09-08T09:21:54.991851"
    }, {
        "id": 6,
        "actionBy": "Sysadmin",
        "eventAction": "REMOVE_IMAGE",
        "Description": "Test description"       
        "actionDate": "2022-09-08T13:55:00.469676"
    }
]

Now I want to use a select(in Vuetify it's a v-select). Where I want to get the select options like this:

[
  { value: 'CREATED', count: 1 },
  { value: 'MODIFIED', count: 2 },
  { value: 'REMOVE_IMAGE', count: 3 },
]

I found some ways, but it doesn't feel really clean. I want to know if there is a efficient way to do this. So it doesn't look dirty. ;-)


Solution

  • You can use a group by from here and a mapping from here to create an array:

    computed: {
        selectOptions() {
            const obj = this.events.reduce((ar, x) => {
               ar[x.eventAction] = (ar[x.eventAction] || 0) + 1;
               return ar;
            }, {});
            return Object.keys(obj).map(key => ({value: key, count: obj[key]}));
        }