I am attempting to dynamically create a query string based on three form inputs. Only inputs that are used should be added to the string.
To do this, I used the following:
let filter = { CustomerName: "Me", AccountNumber: "", "Author/Title": "You" }
const result = Object.entries(filter).map(([key, value]) => {
if (value) {
// if input was used, return given string
console.log(`${key} eq '${value}'`)
return `${key} eq '${value}'`
}
})
console.log(result); // output is ["CustomerName eq 'Me'", undefined, "Author/Title eq 'You'"]
let filterStr = ''
result.forEach(element => {
if (element) {
filterStr += ` and ${element}`
}
});
console.log(filterStr.replace(" and", "")) // output is "CustomerName eq 'Me' and Author/Title eq 'You'"
The final output is correct, however this seems like a redundant way to getting to the final result.
How can I clean this up to be less redundant and increase readability?