简体   繁体   中英

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM