1

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?

3 Answers 3

1

Try below code, if this is what you are looking for.

let filter = { CustomerName: "Me", AccountNumber: "", "Author/Title": "You" }

let str = Object.keys(filter)
    .filter(key => filter[key])
    .map(key => `${key} eq '${filter[key]}'`)
    .join(' and ');

console.log(str);
Sign up to request clarification or add additional context in comments.

Comments

0

You could filter first, then get the mapped strings and join the result with only one and at between the last two values.

const nice = array => array.concat(array.splice(-2, 2).join(' and ')).join(', ');

var filter = { foo: 'bar', CustomerName: "Me", AccountNumber: "", "Author/Title": "You" },
    result = Object
        .entries(filter)
        .filter(([, value]) => value)
        .map(([key, value]) => `${key} eq '${value}'`);

console.log(nice(result));

Comments

0

let filter = { CustomerName: "Me", AccountNumber: "", "Author/Title": "You"}

let formattedObj = Object.keys(filter).filter(key => filter[key]).map(key => `${key} eq \'${filter[key]}\'`)
console.log(formattedObj.join(' and '))

Comments

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.