0

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. ;-)

Juraj
  • 192
  • 2
  • 9
  • How do you expect to generate the text "image removed"? – Nick Sep 14 '22 at 08:35
  • Got a function for that. Like: displayTypeText(item) witch (item.eventAction) { case 'CREATED': return 'created'; case 'MODIFIED': return 'modified'; case 'REMOVE_IMAGE: return 'image removed'; ` – Juraj Sep 14 '22 at 08:59
  • Removed the text. To prevent misunderstandings. – Juraj Sep 14 '22 at 09:31
  • Use one of the groupbys [here](https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-an-array-of-objects) and then convert the object to an array using Object.keys like [here](https://stackoverflow.com/questions/38824349/how-to-convert-an-object-to-an-array-of-key-value-pairs-in-javascript)? – Yitz Sep 14 '22 at 09:59

1 Answers1

1

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]}));
    }
Yitz
  • 946
  • 4
  • 8
  • 1
    Fantastic! That is really clean. My attempt had like 20 rows of code.. ^_^ Thank you! – Juraj Sep 14 '22 at 11:51