I'm newer to Vue JS and am trying to use what they offer to go through a JSON array to make multiple arrays based on a shared object prop value. Based on this JSON:
{
fields: [
{
"group": "group1",
"label": "label1",
"value": "value1",
},
{
"group": "group1",
"label": "label2",
"value": "value2",
},
{
"group": "group2",
"label": "label3",
"value": "value3",
},
{
"group": "group2",
"label": "label4",
"value": "value4",
},
],
}
I need to make different arrays per "group", so I need to make a different array for "group1" values, then as the loop gets to "group2" values stop and make a new array of all the group 2 objects. The "group" values could be anything, I will not know them ahead of time.
I need to end up with this:
group1Fields: [
{
"group": "group1",
"label": "label1",
"value": "value1",
},
{
"group": "group1",
"label": "label2",
"value": "value2",
}
],
group2Fields: [
{
"group": "group2",
"label": "label3",
"value": "value3",
},
{
"group": "group2",
"label": "label4",
"value": "value4",
}
]
I'm currently investigating array mapping and even using a computed property or method, would appreciate any advice.
Currently studying the YouTube channel "LearnVue" on loops in Vue. https://www.youtube.com/c/LearnVue
CodePudding user response:
You can use filter
:
const app = Vue.createApp({
data() {
return {
fields: [
{"group": "group1", "label": "label1", "value": "value1",},
{"group": "group1", "label": "label2", "value": "value2",},
{"group": "group2", "label": "label3", "value": "value3",},
{"group": "group2", "label": "label4", "value": "value4",},
],
grp: null
};
},
computed: {
groups() {
return [...new Set(this.fields.map(f => f.group))]
},
filteredGroups() {
return this.grp ? this.fields.filter(g => g.group === this.grp) : this.fields
}
}
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<div v-for="(item, i) in groups" :key="i">
<button @click="grp = item">{{ item }}</button>
</div>
<ul>
<li v-for="(group, i) in filteredGroups" :key="i">
{{ group }}
</li>
</ul>
</div>