Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use lodash to lowercase internal array element

I have this object

ob = {
 timePeriod: "Month",
 device: ["A", "B"]
}

when i use

x=_.mapValues(ob, _.method('toLowerCase'))

x is

 timePeriod: "month",
 device: undefined

it is not able to lowercase device array.

like image 827
Manish Kumar Avatar asked Mar 14 '23 05:03

Manish Kumar


2 Answers

Array dont have toLowerCase function. Change to below

x = _.mapValues(ob, function(val) {
  if (typeof(val) === 'string') {
   return val.toLowerCase(); 
  }
  if (_.isArray(val)) {
    return _.map(val, _.method('toLowerCase'));
  }
});

JSON.stringify(x) // {"timePeriod":"month","device":["a","b"]}
like image 77
Jagdish Idhate Avatar answered Mar 15 '23 19:03

Jagdish Idhate


var ob = {
    timePeriod: "Month",
    device: ["A", "B"]
}
var lowerCase = _.mapValues(ob, function(value){
    return _.isArray(value) ? _.map(value, _.toLowerCase) : _.toLowerCase(value);
})
like image 22
stasovlas Avatar answered Mar 15 '23 18:03

stasovlas