I need to map a JavaScript object to query string parameters. I found several related questions on this site, but none that fully met my needs.
The object will consist of strings and arrays, but will not be nested. Here is an example:
var filters = {
make: ["Ford", "Honda"],
year: [],
color: "Black",
model: ""
}
Here is the code I have:
mapQueryStringParameters = function (params) {
return params
? '?' + Object.entries(params)
.flatMap(([key, value]) => [value].flat().map(v => [key, v]))
.map(it => it.join("="))
.join("&")
: "";
}
The above code produces the following result, which is almost correct:
"?make=Ford&make=Honda&color=Black&model="
It correctly omits the year empty array, but adds an property for model, which is an empty string. How can I modify so that it omits any property with an empty string?
make[]=?[]to multi-valued entries (see this answer for more information than anyone could possibly want :))