Skip to the solution
MediumDSAAsked in 20246 min read

Implement objectMap(obj, fn) — Transform Every Value via Object.entries/fromEntries

4.1k views

The problem

Problem, as an interviewer would state it: "Implement objectMap(obj, fn) — transforming EVERY value of a plain object via fn, keeping the same keys, matching a real, common Array.prototype.map-equivalent for objects, built directly on Object.entries/Object.fromEntries."

Examples:

Code
objectMap({a:1, b:2, c:3}, v => v * 2); // {a:2, b:4, c:6}

Clarifying questions expected:

  • Should the callback receive the KEY (and index) as additional arguments, matching Array.prototype.map's own real, familiar signature?
  • Should the original object remain completely untouched, with a genuinely new object returned?
  • Should this bank's own already-covered Object.fromEntries polyfill be reused as a building block here?

Code / implementation expected: Yes — real, direct proof of correct value transformation, confirmation the key is correctly passed as the callback's second argument, and confirmation the original object is never mutated.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: objectMap() correctly transforms every value while keeping keys unchanged, with the key correctly passed as the callback's second argument

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 46 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Observable map/filter operators

Continue