I currently create an object on page load with all possible key/value pairs and use true or false to determine their state. It would be more efficient if only items that were true were present though.
Sample data:
filter = {
"country": 1,
"Age Group": {
2: false,
3: true,
4: false,
5: false,
6: false,
7: false
},
"Gender": {
1: false,
2: false
},
"NEWSEC": {
1: false,
2: true,
3: false,
4: false,
5: false
},
"Telco_Segment": {
1: true,
2: true,
3: true,
4: false,
5: false,
6: false
}
};
function:
function facetBuilder(key, val)
{
if(key == 'country')
{
filter.country = val;
}
else
{
if( filter[key][val] == true )
{
filter[key][val] = false;
}
else
{
filter[key][val] = true;
}
}
console.log(filter);
}
Problem:
The function I use to apply these filters loops through them, so it would be more beneficial if I only had the objects such as “Age Group” present if it contained any values. In fact, it would be nice to have something like the following:
filter = {
"country": 1,
"Age Group": [3],
"NEWSEC": [2],
"Telco_Segment": [1,2,3]
};
calling facetBuilder would essentially add/remove an object based on the presence of value(s) for that object.
I’m drawing a blank on how to approach this one.
You don’t need to explicitly check for
true. You can check for the existence for an entry by doing something like this:However if the value associated with that key is
0, then this is a problem, so it’s better to do:The reason you want to use
typeofin this case is that a direct comparison againstundefinedcan be problematic due to the possibility ofundefinedbeing overwritten by other code:Then your code would look like this:
Another thing, when checking for a true value, it’s enough to say
You don’t have to do:
or
Another way to check for the existence of a property is to use the
inoperator:I’m assuming this is what you want to do. If not, please let me know.