使用lodash来小写内部数组元素

时间:2016-02-22 10:37:07

标签: javascript lodash

我有这个对象

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

当我使用

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

x

 timePeriod: "month",
 device: undefined

它无法小写device数组。

2 个答案:

答案 0 :(得分:5)

数组没有toLowerCase函数。 改为下面

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

答案 1 :(得分:1)

var ob = {
    timePeriod: "Month",
    device: ["A", "B"]
}
var lowerCase = _.mapValues(ob, function(value){
    return _.isArray(value) ? _.map(value, _.toLowerCase) : _.toLowerCase(value);
})