Skip to content Skip to sidebar Skip to footer

Lowercase Of Object Value In Array With Underscore Js

Let's say I have this JSON data in a data variable [{'id':'1','module_id':'1','title':'Test', 'start_date':'2012-11-12' 'end_date':'2012-11-18'}, {'id':'8','module_id':'1','titl

Solution 1:

You can do this easily with Lo Dash's _.mapValues function:

_.mapValues(objs, function(s){
  return _.isString(s) ? s.toLowerCase() : s;
});

Solution 2:

If you're already dealing with an object (or parsed JSON), you can loop and create a new one:

var objs = [{"id":"1","module_id":"1","title":"Test", "start_date":"2012-11-12", "end_date":"2012-11-18"},{"id":"8","module_id":"1","title":"This is OK", "start_date":"2013-01-14","end_date":"2013-01-31"}];

varout = [];
for(var i=0; i<objs.length; i++) {
    var outObj = {}
    for(var prop in objs[i]) {
        varval = objs[i][prop];
        if(prop === 'title') {
            val = val.toLowerCase();  
        }
        outObj[prop] = val;
    }
    out.push(outObj);
}
console.log(out);

http://jsfiddle.net/uY36J/

Solution 3:

If you have array of objects:

for(var i = 0; i < array.length; i++) {
   for (var prop in array[i])
       // condition herearray[i][prop] = array[i][prop].toLowerCase();
}

console.log(array)

Same with underscore (I don't think it's much shorter - you still need two loops here. More readable - maybe, but not shorter)

_.each(array, function(obj) {
    _.each(obj, function(value, key) { 
        // condition here        
        obj[key] = value.toLowerCase();
    });
});

Solution 4:

You can separate the object in two arrays, one with the keys and the other with the values, then use _.map to lowercase the strings.

var objs = [{"id":"1","module_id":"1","title":"Test", "start_date":"2012-11-12", "end_date":"2012-11-18"},{"id":"8","module_id":"1","title":"This is OK", "start_date":"2013-01-14","end_date":"2013-01-31"}];

 _.map(objs,function(element) {
     return  _.object(_.keys(element), _.values(element).map(function(value) { 
         return _.isString(value)? value.toLowerCase():value; 
     }));
 });

you see, I'm checking if it's a string we're dealing with, to avoid calling toLowerCase on other types.

Lowercasing both keys and values is trivial as well

 _.map(objs,function(element) {
     return  _.object(
         _.keys(element).map(function(key) { 
             return _.isString(key)? key.toLowerCase():key; 
         }),
         _.values(element).map(function(value) { 
             return _.isString(value)? value.toLowerCase():value; 
         })
     );
 });

Caveat: this will not operate on nested objects. ¯\_(ツ)_/¯

Post a Comment for "Lowercase Of Object Value In Array With Underscore Js"