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