@ -6,18 +6,19 @@ tags: object,recursion,advanced
|
||||
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(obj)` to iterate over the object's keys.
|
||||
Use `Object.keys(obj)` 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, f) =>
|
||||
const deepMapKeys = (obj, fn) =>
|
||||
Array.isArray(obj)
|
||||
? obj.map(val => deepMapKeys(val, f))
|
||||
? obj.map(val => deepMapKeys(val, fn))
|
||||
: typeof obj === 'object'
|
||||
? Object.keys(obj).reduce((acc, current) => {
|
||||
const key = fn(current);
|
||||
const val = obj[current];
|
||||
acc[f(current)] =
|
||||
val !== null && typeof val === 'object' ? deepMapKeys(val, f) : (acc[f(current)] = val);
|
||||
acc[key] =
|
||||
val !== null && typeof val === 'object' ? deepMapKeys(val, fn) : val;
|
||||
return acc;
|
||||
}, {})
|
||||
: obj;
|
||||
@ -51,4 +52,4 @@ const upperKeysObj = deepMapKeys(obj, key => key.toUpperCase());
|
||||
}
|
||||
}
|
||||
*/
|
||||
```
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user