Exercise 11: Transform Object Keys

Problem Statement

Function `transformKeys(obj, fn)` banao jo object ke sabhi keys ko transform kare. Example: transformKeys({name: "John", age: 30}, k => k.toUpperCase()) => {NAME: "John", AGE: 30}

Sample Output:

transformKeys({name: "John", age: 30}, k => k.toUpperCase()) => {NAME: "John", AGE: 30}
transformKeys({a: 1}, k => `prefix_${k}`) => {prefix_a: 1}

Solution

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

Explanation

Overall Goal:

  • Object keys ko transform function se modify karna.

Real world:

  • Data transformation: key formatting.
  • API mapping: key conversion.