Files
30-seconds-of-code/snippets/deep-map-keys.md
Angelos Chalaris 61200d90c4 Kebab file names
2023-04-27 21:58:35 +03:00

59 lines
1.2 KiB
Markdown

---
title: Deep map object keys
tags: object,recursion
cover: duck-plants
firstSeen: 2018-11-29T15:22:53+02:00
lastUpdated: 2020-09-15T16:28:04+03:00
---
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`.
```js
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;
```
```js
const obj = {
foo: '1',
nested: {
child: {
withArray: [
{
grandChild: ['hello']
}
]
}
}
};
const upperKeysObj = deepMapKeys(obj, key => key.toUpperCase());
/*
{
"FOO":"1",
"NESTED":{
"CHILD":{
"WITHARRAY":[
{
"GRANDCHILD":[ 'hello' ]
}
]
}
}
}
*/
```