5
\$\begingroup\$

I wrote a small snippet to convert object keys to lowercase. I would like to listen about the ways to improve the following code:

function toLowerCaseKeys(obj) {
  return Object.keys(obj).reduce(function(accum, key) {
    accum[key.toLowerCase()] = obj[key];
    return accum;
  }, {});
}

console.clear();
console.log(toLowerCaseKeys({'Foo': true}).foo);
console.log(toLowerCaseKeys({'FoO': true}).foo);
\$\endgroup\$
4
  • \$\begingroup\$ It's pretty much a trivial piece of code, no? What are you looking to improve upon? You noted "performance" as one of your tags. Have you done anything to compare performance of the approach of using Object.keys().reduce() vs. just iterating the object properties (i.e. for (key in obj) { ... }) In other words, if you are worried about performance of this method, have you done anything to test the performance such that you are concerned with your approach? \$\endgroup\$
    – Mike Brant
    May 3, 2017 at 18:24
  • 1
    \$\begingroup\$ @MikeBrant The code itself is trivial, but the actual task "convert object keys to lowercase" can be accomplished in different ways. There are many issues to deal with: what if a converted lower case attribute already exists? what about the prototype? is a Proxy better suited? Perhaps CodeYogi could point out what his/her concerns are. \$\endgroup\$
    – le_m
    May 3, 2017 at 21:06
  • \$\begingroup\$ @le_m right, I have written this small snippet and thinking that if it could be written in any better way, the better can mean more performant, flexible etc. \$\endgroup\$
    – CodeYogi
    May 4, 2017 at 3:26
  • \$\begingroup\$ This reeks of premature optimization and possibly the XY problem. \$\endgroup\$
    – Joseph
    May 4, 2017 at 8:01

1 Answer 1

4
\$\begingroup\$

If you can go ES6, you can get a more concise version:

Object.keys(o).reduce((c, k) => (c[k.toLowerCase()] = o[k], c), {});

Now, if one or more strings lowercase into the same string, expect only one of them to remain.

\$\endgroup\$
1
  • \$\begingroup\$ What about error handling or edge cases? \$\endgroup\$
    – CodeYogi
    May 3, 2017 at 18:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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