7

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()
Jesus_Maria
  • 1,027
  • 4
  • 12
  • 23
  • 1
    Simply iterate over the properties of the object. If you don't know how, see http://stackoverflow.com/q/85992/218196 . – Felix Kling Nov 19 '15 at 16:54

6 Answers6

23

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

_.mapValues(z, _.method('toLowerCase'));
Adam Boduch
  • 10,427
  • 3
  • 27
  • 38
  • 3
    If your object has non-strings values it will remove them. its best to check type `_.mapValues(objs, function(s){ return _.isString(s) ? s.toLowerCase() : s; });` **Source:** http://stackoverflow.com/questions/15510712/lowercase-of-object-value-in-array-with-underscore-js – Simo D'lo Mafuxwana Nov 24 '16 at 05:11
7

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?

Molomby
  • 4,715
  • 31
  • 25
  • Browser support for this is ok but not great. YMMV.. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Browser_compatibility – Molomby Dec 11 '16 at 23:47
5

In JavaScript, you can iterate through the object's keys using a for...in loop:

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

for(var i in z) {
  z[i]= z[i].toLowerCase();
}

console.log(z);

I don't know if lodash can improve on that.

Rick Hitchcock
  • 34,132
  • 4
  • 45
  • 75
2

In vanilla js:

Object.keys(z).forEach(function ( key ) {
    z[key] = z[key].toLowerCase();
});

Lodash might have shorter forEach syntax.

Shilly
  • 8,261
  • 1
  • 17
  • 24
1

If you want a solution without lodash, you could use Object.keys and Array.prototype.reduce:

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

var lowerZ = Object.keys(z).reduce(function(obj, currentKey) {
    obj[currentKey] = z[currentKey].toLowerCase();
    return obj;
}, {});
nils
  • 23,672
  • 5
  • 66
  • 79
0

CoffeeScript solution:

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

for key, val of z
    z[key] = val.toLowerCase()
Tomasz Jakub Rup
  • 10,083
  • 7
  • 48
  • 49