Lowercase of object value in array with underscore

2019-08-02 09:14发布

问题:

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","title":"This is OK",
  "start_date":"2013-01-14","end_date":"2013-01-31"}]

How do I use underscore.js to get following result?

[{"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"}]

Can I do this with invoke ?

回答1:

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

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


回答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"}];

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

http://jsfiddle.net/uY36J/



回答3:

If you have array of objects:

for(var i = 0; i < array.length; i++) {
   for (var prop in array[i])
       // condition here
       array[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();
    });
});


回答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. ¯|(ツ)