0

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?

5
  • You are missing some code becuase return result should be inside another function. Commented Jul 9, 2019 at 18:24
  • 1
    You are reinventing reduce() Commented Jul 9, 2019 at 18:25
  • @epascarello That's what my question is about.. Kindly make an answer. Commented Jul 9, 2019 at 18:25
  • 2
    Follow the example? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jul 9, 2019 at 18:26
  • You say “without having to fill the result object”, but why do you have to do this? Commented Jul 9, 2019 at 18:30

2 Answers 2

3

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)])
)
Sign up to request clarification or add additional context in comments.

2 Comments

Note for readers: fromEntries is ECMAScript 2019 and is not supported in all browsers/engines as of this writing (see the support grid at the bottom of the linked doc).
It actually has pretty decent support now days (all except IE/Edge/Opera), and it's easy to polyfill.
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.