I am trying to iterate the object using v-for.
exampleObject =[a,b,c,d] Requirement = if a exist in exampleObject, show only a, else show b, c, d.
<div v-if="checklist.types">
<div v-for="type in checklist.types">
<div v-if="type.Name == 'Module1'">
show module 1
</div>
<div v-else>
<span>{{type.Name }}</span>
</div>
</div>
</div>
The above shows all values as the condition is checked within For Loop. Is there a way to iterate and check the object at the beginning.
Advertisement
Answer
I’d use a computed property that returns an array containing…
- Only
a/Module1if it exists - The entire
exampleObject/checklist.typesotherwise
Then you can just iterate that computed property
export default {
data: () => ({
checklist: {
types: [/* whatever */]
}
}),
computed: {
modules: ({ checklist: { types } }) => {
const module1 = types.find(({ Name }) => Name === "Module1")
return module1 ? [ module1 ] : types
}
}
}
<div v-for="module in modules" :key="module.Name">
<span>{{ module.Name }}</span>
</div>