Reputation: 1433
I have a function that takes in a variety of filter values (the values for each filter are stored within an array) and stores them collectively within an object. My thinking here is that by doing this I should be able to stack the values - i.e. if I have a value for one filter, and then a second filter is selected, this should not wipe out the first filter value, as long as I'm returning the full object - which is what I'm doing. However, for some reason what's happening is that the selection of a new filter wipes out the value of the previously selected filter. Here's my code:
public filterByTypes(value, type) {
let location = '', agency = '', zipcode = '', firstName = '', lastName = '', state = '';
if (value && type && type === 'location')
{
location = value;
}
if (value && type && type === 'agency')
{
agency = value;
}
else if (value && type && type === 'zip')
{
zipcode = value;
}
else if (value && type && type === 'firstName')
{
firstName = value;
}
else if (value && type && type === 'lastName')
{
lastName = value;
}
else if (value && type && type === 'state')
{
state = value;
}
return { location, agency, zipcode, firstName, lastName, state };
}
As I say, since I'm returning an object with each of the value params, it seems to me this should return all of the stacked values, not just the most recently selected on. However, that's what's happening - when a new filter is selected, it wipes out the value from the previous/different filter. What am I missing here?
Upvotes: 0
Views: 35
Reputation: 3214
You need to pass your returned object in the functions as well
function processByTypes(value, type, filters) {
if (value && type && type === 'location')
{
filters.location = value;
}
if (value && type && type === 'department')
{
filters.department = value;
}
else if (value && type && type === 'zip')
{
filters.zipcode = value;
}
else if (value && type && type === 'firstName')
{
filters.firstName = value;
}
else if (value && type && type === 'lastName')
{
filters.lastName = value;
}
else if (value && type && type === 'branch')
{
filters.branch = value;
}
else if (value && type && type === 'active')
{
filters.active = value;
}
return filters;
}
let filters = {};
processByTypes('Sales', 'department', filters);
processByTypes('Americas', 'location', filters);
//and so on
Upvotes: 0
Reputation: 2082
you are resetting all of your keys every time you run the function. try instead:
var filters = {};
function setFilter(type, value) {
if(value && type) { filters[type] = value; }
return filters;
}
if you're managing an object, 'filters' can be a property and 'setFilter' can be a method.
Upvotes: 3