F
F
fessss2021-02-19 15:50:34
Vue.js
fessss, 2021-02-19 15:50:34

How to filter an array of objects by keys?

How can I display an array of objects filtered by key in the v-expansion-panels component?
There is such a component

<v-expansion-panels>
    <v-expansion-panel
      v-for="(item,i) in arr"
      :key="i"
    >
      <v-expansion-panel-header>
        {{ item.group }}
      </v-expansion-panel-header>
      <v-expansion-panel-content></v-e{{item.name}}xpansion-panel-content>
    </v-expansion-panel>
  </v-expansion-panels>


And there is such an array
const arr = [
    {
        name: 'name1',
        group: 'test1',
    },
    {
        name: 'name2',
        group: 'test1',
    },
    {
        name: 'name3',
        group: 'test1',
    },
    {
        name: 'name4',
        group: 'test2',
    },
    {
        name: 'name5',
        group: 'test2',
    },
    {
        name: 'name6',
        group: 'test2',
    },
]


It is necessary to output so that under one tab there are objects with the same group.

test1 => name1, name2, name3
test2 => name4, name5, name6

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-02-19
@fessss

computed: {
  grouped() {
    return this.arr.reduce((acc, n) => ((acc[n.group] ||= []).push(n), acc), {});
  },
},

<v-expansion-panels>
  <v-expansion-panel v-for="(items, groupName) in grouped">
    <v-expansion-panel-header>{{ groupName }}</v-expansion-panel-header>
    <v-expansion-panel-content>
      <div v-for="n in items">{{ n.name }}</div>
    </v-expansion-panel-content>
  </v-expansion-panel>
</v-expansion-panels>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question