Exercise 14: Map Object Values

Problem Statement

Function `mapValues(obj, fn)` banao jo object ke sabhi values ko transform kare. Example: mapValues({a: 1, b: 2}, x => x * 2) => {a: 2, b: 4}

Sample Output:

mapValues({a: 1, b: 2}, x => x * 2) => {a: 2, b: 4}
mapValues({x: "hello"}, s => s.toUpperCase()) => {x: "HELLO"}

Solution

const mapValues = (obj, fn) => {
  return Object.keys(obj).reduce((acc, key) => {
    acc[key] = fn(obj[key], key);
    return acc;
  }, {});
};

Explanation

Overall Goal:

  • Object values ko transform function se modify karna.

Real world:

  • Data transformation: value mapping.
  • Calculations: value operations.