HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Transform the keys of a JavaScript object

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptobjecttransformthekeys

Problem

JavaScript objects are a fundamental data structure in the language, and they are used to store collections of key-value pairs. Transforming object keys can come in handy in many different situations, but requires a little bit of work to get it right.
Given an object and a function, you can generate a new object by mapping the keys of the original object using the provided function.
In order to do so, you can use Object.keys() to iterate over the object's keys and Array.prototype.reduce() to create a new object with the same values and mapped keys using the provided function, fn.
> [!NOTE]
>

Solution

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

mapKeys({ a: 1, b: 2 }, (val, key) => key + val); // { a1: 1, b2: 2 }


In order to do so, you can use Object.keys() to iterate over the object's keys and Array.prototype.reduce() to create a new object with the same values and mapped keys using the provided function, fn.
> [!NOTE]
>
> Similarly, you can transform the values of an object using the same approach. Simply use Object.entries() or Object.values() instead of Object.keys().
The previous snippet only works for the keys at the first level of the object. In order to transform nested keys, you'll have to use recursion.
Again, using Object.keys() to iterate over the object's keys, you can use Array.prototype.reduce() to create a new object with the same values and mapped keys using the provided function, fn. If the value of a key is an object, you can call the function recursively to transform its keys as well.

Code Snippets

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

mapKeys({ a: 1, b: 2 }, (val, key) => key + val); // { a1: 1, b2: 2 }
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' ]
        }
      ]
    }
  }
} */
const renameKeys = (keysMap, obj) =>
  Object.keys(obj).reduce(
    (acc, key) => ({
      ...acc,
      ...{ [keysMap[key] || key]: obj[key] }
    }),
    {}
  );

const obj = { name: 'Bobo', job: 'Front-End Master', shoeSize: 100 };
renameKeys({ name: 'firstName', job: 'passion' }, obj);
// { firstName: 'Bobo', passion: 'Front-End Master', shoeSize: 100 }

Context

From 30-seconds-of-code: transform-object-keys

Revisions (0)

No revisions yet.