Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert all object values to lowercase with lodash

I have an object:

z = {x: 'HHjjhjhHHHhjh', y: 'YYYYY', c: 'ssss'}

I need to convert all values to lowercase

z = {x: 'hhjjhjhhhhhjh', y: 'yyyyy', c: 'ssss'}

How to do this in one time, maybe with lodash? for now I am doing:

z.x = z.x.toLowerCase()
z.y = z.y.toLowerCase()
z.c = z.c.toLowerCase()
like image 760
Jesus_Maria Avatar asked Nov 19 '15 16:11

Jesus_Maria


Video Answer


2 Answers

Using lodash, you can call mapValues() to map the object values, and you can use method() to create the iteratee:

_.mapValues(z, _.method('toLowerCase'));
like image 162
Adam Boduch Avatar answered Oct 02 '22 12:10

Adam Boduch


A lot of the stuff you'd use Lodash for you can do quite easily in ES6/ES2015. Eg, in this case you could:

var z = { x: 'HHjjhjhHHHhjh', y: 'YYYYY', c: 'ssss' };
var y = Object.keys(z).reduce((n, k) => (n[k] = z[k].toLowerCase(), n), {});

console.log(y);
// { x: 'hhjjhjhhhhhjh', y: 'yyyyy', c: 'ssss' }

Pretty neat, eh?

like image 20
Molomby Avatar answered Oct 02 '22 10:10

Molomby