Edgaras Karka
Edgaras Karka

Reputation: 7852

How to change each value in JS object using Lodash

I have an object like:

{ 
  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
}

my goal is to get new same structure object, but with each value multiplied by 100 and get the same structure.

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

Upvotes: 0

Views: 456

Answers (3)

Ori Drori
Ori Drori

Reputation: 191966

With lodash/fp you can create a function with _.mapValues() and _.multiply() that iterates the object, and multiplies each value by 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>

Upvotes: 1

ryeballar
ryeballar

Reputation: 30088

You can use mapValues() to solve this problem, together with a callback to transform each value.

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>

Upvotes: 2

Yusuf Kayikci
Yusuf Kayikci

Reputation: 332

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

Upvotes: 0

Related Questions