\$\begingroup\$
\$\endgroup\$
4
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);
asked May 3, 2017 at 17:17
1 Answer 1
\$\begingroup\$
\$\endgroup\$
1
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.
answered May 3, 2017 at 17:55
-
\$\begingroup\$ What about error handling or edge cases? \$\endgroup\$CodeYogi– CodeYogi2017年05月03日 18:04:29 +00:00Commented May 3, 2017 at 18:04
default
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\$