0

I'm building a filter for a search. Everything worked fine before since we only allowed 1 filter at a time. So I'd get a return like this:

var returnVal = "&filterName=filterProperty"
var filterFields = returnVal.split(['=']);
var filterCategory = filterFields[0];
var filterCatSplit = filterCategory.substr(1);
var filterTitle = filterFields[1];

<h4>filter title</h4>
<ul>
    <li>filter one</li>
</ul>

i'd just get the returnVal and split it at the '='

Now we're going to allow multiple values and I'm not sure how to get them all onto the page in a nice list. Now, returnVal can look like this:

var returnVal = "&sizeFilterName=filterProperty,filterPropery&colorFilterName=filterProperty,filterProperty"

I now need this to return like this (or something like this)

<h4>Size Filter Name</h4>
<ul>
    <li>Size Filter One</li>
    <li>Size Filter Two etc</li>
</ul>

<h4>Color Filter Name</h4>
<ul>
    <li>Color Filter One</li>
    <li>Color Filter Two etc</li>
</ul>

I've never had to split and slice so many variants before. I'm a bit lost. I hope this is enough to get an idea of what I'm trying to do.

Thanks!

2
  • Did you try splitting on &, then taking each item in that list and splitting on = and ,? And then using the property names to decide where each list of values has to go? Commented Jan 18, 2018 at 22:41
  • i thought about it, but that seemed like an inefficient way to do it. like its the 'long way' and not the right way Commented Jan 18, 2018 at 23:18

1 Answer 1

1

You can pass returnVal to URLSearchParams() then .split() the value by "," perform tasks using the returned array

let returnVal = "&sizeFilterName=filterProperty,filterPropery&colorFilterName=filterProperty,filterProperty";
let params = Array.from([...new URLSearchParams(returnVal)]
             , ([key, value]) => [key, value.split(",").filter(Boolean)]);
// do stuff with `params`
params.forEach(([key, value]) => 
  document.body.insertAdjacentHTML("beforeend", `<h4>Size ${key}</h4>
<ul>
    ${value.map(prop => `<li>Color ${prop}</li>`).join("")}
</ul>`)
);

Sign up to request clarification or add additional context in comments.

3 Comments

this looks like it'll work. im away from my comp to try but as soon as i get there i will. thanks!
Just noticed the Color filterProperty is running for both lists. One should be 'Size filterProperty' and the other 'Color filterProperty' - I'm going to try to work this out
@rebel84 Noticed that only upon you mentioning it. Originally did not include the string "Color". You should be able to include and use the index argument of .map() to check if "Size" or "Color" is the text set at the element before prop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.