Reputation: 375
There are two arrays, I receive data from the backend. In the first array of the city, in the second, delivery time.
First:
region: {
type: Array,
default: () => []
},
Second:
deliveryTime: {
type: Array,
default: () => []
}
come as a regular array, key-value. (for example-- Region: [{"name": "Boston"}, {"name":"Detroit"}, {""}];
and DeliveryTime: [{"name": "Detroit","delivery_time: "2-7""},{"name": "Boston","delivery_time": "1-3"},{"}]
)
If the names are the same, I need to output delivery time.
I tried:
<div v-for='(reg, index) in deliveryTime' :key='index' >
<span :class='{ "reg": findTime(reg) }'> {{ reg }} </span>
</div>
///////////////
findTime(reg) {
return this.region.includes(reg);
}
Finds matching cities, but how to refer to delivery_time
Upvotes: 0
Views: 64
Reputation: 138336
Both array elements contain the region name in the name
property, so findTime()
needs to read that property from this.region[]
and from reg
(i.e., the deliveryTime[]
array element).
Use Array.prototype.some()
to compare each region's name
to the delivery time's region:
export default {
methods: {
findTime(reg) {
return this.region.some(r => r.name === reg.name)
}
}
}
Then to conditionally display the item, use v-if
in your template:
<span v-if="findTime(reg)">{{ reg.name }}</span>
Another way to solve the problem is to compute the filtered results:
<template>
<div v-for='(reg, index) in computedDeliveryTime'>
<span> {{ reg.name }} </span>
</div>
</template>
<script>
export default {
computed: {
computedDeliveryTime() {
return this.deliveryTime.filter(d => {
return this.region.some(r => r.name === d.name)
})
}
}
}
</script>
Upvotes: 2