Deep map object keys

JavaScript, Object, Recursion · Sep 15, 2020

Deep maps an object's keys.

  • Creates an object with the same values as the provided object and keys generated by running the provided function for each key.
  • Use Object.keys() to iterate over the object's keys.
  • Use Array.prototype.reduce() to create a new object with the same values and mapped keys using fn.
const deepMapKeys = (obj, fn) =>
  Array.isArray(obj)
    ? obj.map(val => deepMapKeys(val, fn))
    : typeof obj === 'object'
    ? Object.keys(obj).reduce((acc, current) => {
        const key = fn(current);
        const val = obj[current];
        acc[key] =
          val !== null && typeof val === 'object' ? deepMapKeys(val, fn) : val;
        return acc;
      }, {})
    : obj;
const obj = {
  foo: '1',
  nested: {
    child: {
      withArray: [
        {
          grandChild: ['hello']
        }
      ]
    }
  }
};
const upperKeysObj = deepMapKeys(obj, key => key.toUpperCase());
/*
{
  "FOO":"1",
  "NESTED":{
    "CHILD":{
      "WITHARRAY":[
        {
          "GRANDCHILD":[ 'hello' ]
        }
      ]
    }
  }
}
*/

More like this

  • Map object keys

    Maps the keys of an object using the provided function, generating a new object.

    JavaScript, Object · Oct 21, 2020

  • Get nested value in object based on array of keys

    Gets the target value in a nested JSON object, based on the keys array.

    JavaScript, Object · Oct 19, 2020

  • Deep merge objects

    Deeply merges two objects, using a function to handle keys present in both.

    JavaScript, Object · Jul 25, 2021