Reputation: 1150
I have this array of objects:
obj=
[{name: 'joe', job: 'teacher', city: 'miami'},
{name: 'bill', job: 'police', city: 'yorkshire'},
{name: 'sarah', job: 'driver', city: 'michigan'}]
And I have a dropdown menu with options like this:
<select v-model="selected">
<option>blue</option>
<option>green</option>
<option>black</option>
<option>all</option>
</select>
and then if one of them is selected I associate them with an object from the array:
if (selected === "blue") {
optionSelected = 'joe'
} else if (selected === "green") {
optionSelected = 'bill'
} else if (selected === "black") {
optionSelected = 'sarah'
} else if (selected === "all") {
// what should go here?
}
And I filter through it like this:
obj = obj.filter(object => object.name === optionSelected)
So now if I select blue
my obj
becomes {name: 'bill', job: 'police', city: 'yorkshire'}
and so on and it is good. However I don't know how to filter for all
. So when it is selected obj
resets to contain all of the values like:
obj=
[{name: 'joe', job: 'teacher', city: 'miami'},
{name: 'bill', job: 'police', city: 'yorkshire'},
{name: 'sarah', job: 'driver', city: 'michigan'}]
How can I do this?
PLEASE NOTE: The architecture of code is setup this way and I cannot change it.
Upvotes: 1
Views: 32
Reputation: 164733
I'd start with an object that maps colours to names so you can avoid all that if..else if
stuff
const colorNameMap = {
blue: 'joe',
green: 'bill',
black: 'sarah',
all: false // totally optional since undefined is falsy
}
Then you simply check if the selected colour matches something in the map. If it doesn't, just return the entire obj
const name = colorNameMap[this.selected]
const filtered = name ? obj.filter(o => o.name === name) : obj
Upvotes: 2