cfoster5
cfoster5

Reputation: 1826

Dynamically create string based on object keys and properties

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?

Upvotes: 1

Views: 69

Answers (3)

Vinay Shrestha
Vinay Shrestha

Reputation: 266

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);

Upvotes: 1

kooskoos
kooskoos

Reputation: 4859

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 '))

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386570

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));

Upvotes: 0

Related Questions