如何使用Lodash更改JS对象中的每个值

时间:2019-03-30 11:21:56

标签: lodash

我有一个像这样的对象

{ 
  home: 78,
  draw: 81,
  away: 36,
  u0_5: 16,
  o0_5: 26,
  u1_5: 10,
  o1_5: 68,
  u2_5: 48,
  o2_5: 50,
  u3_5: 29,
  o3_5: 31,
  u4_5: 50,
  o4_5: 5,
  u5_5: 68,
  o5_5: 56
}

我的目标是获得新的相同结构的对象,但将每个值乘以100并获得相同的结构。

 { 
   home: 7800,
   draw: 8100,
   away: 3600,
   ...
  }

3 个答案:

答案 0 :(得分:1)

您可以使用mapValues()来解决此问题,并使用回调来转换每个值。

const result = _.mapValues(data, v => v * 100);

const data = { 
  home: 78,
  draw: 81,
  away: 36,
  u0_5: 16,
  o0_5: 26,
  u1_5: 10,
  o1_5: 68,
  u2_5: 48,
  o2_5: 50,
  u3_5: 29,
  o3_5: 31,
  u4_5: 50,
  o4_5: 5,
  u5_5: 68,
  o5_5: 56
};

const result = _.mapValues(data, v => v * 100);

console.log(result);
.as-console-wrapper{min-height:100%;top:0!important}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

答案 1 :(得分:1)

使用lodash/fp,您可以使用_.mapValues()_.multiply()创建一个函数,该函数可以迭代对象,并将每个值乘以100:

const fn = _.mapValues(_.multiply(100))

const obj = {"home":78,"draw":81,"away":36,"u0_5":16,"o0_5":26,"u1_5":10,"o1_5":68,"u2_5":48,"o2_5":50,"u3_5":29,"o3_5":31,"u4_5":50,"o4_5":5,"u5_5":68,"o5_5":56}

const result = fn(obj)

console.log(result)
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>

答案 2 :(得分:0)

_.forEach(data, function(value, key) {
       data.key = value*100;
});