2
\$\begingroup\$
    shippingAddress.first_name = shippingAddress.first_name.trim()
    shippingAddress.last_name = shippingAddress.last_name.trim()
    shippingAddress.address1 = shippingAddress.address1.trim()
    shippingAddress.address2 = shippingAddress.address2.trim()
    shippingAddress.phone = shippingAddress.phone.trim()
    shippingAddress.city = shippingAddress.city.trim()
    shippingAddress.province = shippingAddress.province.trim()
    shippingAddress.country = shippingAddress.country.trim()
    shippingAddress.zip = shippingAddress.zip.trim()

What is a more elegant way to write this? I am thinking I can map it somehow or use something similar to Ruby's inject but I'm not sure.

\$\endgroup\$
1
\$\begingroup\$

With single traversal on keys list and trimming all fields of type string:

Object.keys(shippingAddress).forEach((k) => {
    if (typeof shippingAddress[k] == 'string') {
        shippingAddress[k] = shippingAddress[k].trim();
    }
})
\$\endgroup\$
  • \$\begingroup\$ Why is ForEach a superior choice to a for loop? \$\endgroup\$ – McDerp Dec 22 '19 at 5:52
  • \$\begingroup\$ @McDerp, with for loop you would have to declare additional counter variables and control condition checked on each iteration. You don't need that when dealing with object keys \$\endgroup\$ – RomanPerekhrest Dec 22 '19 at 5:54
  • \$\begingroup\$ Is trimming this best done in a function that is mapped to a http action or is this function best abstracted to a /utils/misc.js or something like that? \$\endgroup\$ – McDerp Dec 22 '19 at 6:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.