Miguel Stevens
Miguel Stevens

Reputation: 9201

Map on Javascript object values without extra variable?

I'm using the following piece of code (which is working fine)

  const result = {}
  Object.keys(timers).forEach(key => {
    result[key] = hydrate(timers[key])
  })
  return result
}

I'm wondering if this is possible in one method? So without having to fill the result object?

Upvotes: 0

Views: 65

Answers (2)

epascarello
epascarello

Reputation: 207511

Just use reduce

var timers = {
  a: 2,
  b: 3,
  c: 4
}
 
const hydrate = x => 2*x

var result = Object.entries(timers).reduce((o, [key, value]) => {
  o[key] = hydrate(value)
  return o
}, {})

console.log(result)

without fat arrow

var timers = {
  a: 2,
  b: 3,
  c: 4
}
 
function hydrate (x) { return 2 * x }

var result = Object.entries(timers).reduce(function(o, entry) {
  o[entry[0]] = hydrate(entry[1])
  return o
}, {})

console.log(result)

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 191976

Convert to entries with Object.entries(), iterate the entries with Array.map() and hydrate the values, and convert back to an object with Object.fromEntries():

const fn = timers => Object.fromEntries(
  Object.entries(timers).map(([k, v]) => [k, hydrate(v)])
)

Upvotes: 3

Related Questions