I have a Javascript array:
var peoples = [
{'people':{'sex':'male', 'diet':'vegetarian','favPlaces':['place1','place2']}},
{'people':{'sex':'female', 'diet':'flexitarian','favPlaces':['place2','place3']}},
{'people':{'sex':'male', 'diet':'flexitarian', 'favPlaces':['place4','place1']}}
];
If I select {'sex':['female','male']} && {'diet':['flexitarian']} the output should be ['place2', 'place3', 'place4', 'place1'].
The problem to my code is if I only select 'sex' it will not display result but if I select both a 'sex' and a 'diet' it will display results. I cant figure out how to make my code dynamic, so that the code will filter dynamically when I select a sex or diet or sex and diet and they will show results.
This is my code:
var filterObj = {'sex': ['female', 'male'], 'diet': ['flexitarian']};
for(var p in peoples){
for(var s in filterObj.sex){
for(var d in filterObj.diet){
if((filterObj.sex[s] == peoples[p].people.sex) && (filterObj.diet[d] == peoples[p].people.diet)){
console.log(peoples[p].people.favPlaces);
}
}
}
This is the HTML:
<ul id="sex">
<li><label><input type="checkbox" value="male">Male</label></li>
<li><label><input type="checkbox" value="female">Female</label></li>
</ul>
<ul id="diet">
<li><label><input type="checkbox" value="none">None</label></li>
<li><label><input type="checkbox" value="flexitarian">Flexitarian</label></li>
<li><label><input type="checkbox" value="vegetarian">Vegetarian</label></li>
</ul>