-
-
Save johnloy/b61c545cb150ac0e7ca00142925bedfa to your computer and use it in GitHub Desktop.
Recursively transform key/values in object, including array values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Recursively transform key/values in object, including array values | |
* | |
* Also can act as a basic deep clone method | |
* @param {Object} obj - Object to transform | |
* @param {Object} [transforms={}] - Object containing transformation functions | |
* @param {Function} [transform.keys] - Function for transforming keys from 'obj' | |
* @param {Function} [transform.values] - Function for transforming values from 'obj' | |
* @param {Number} [level=0] - Level of recursion, passed as the 2nd argument to a transform function | |
* @returns {Object} Transformed object | |
* | |
* @example | |
* transformObj({ | |
* apple: 'Green', | |
* orange: 'Orange', | |
* cherry: { | |
* color: 'Red' | |
* } | |
* }, { | |
* keys: (key, level) => { | |
* return level === 0 ? `fruit_${key}` : key; | |
* }, | |
* values: (value) => { | |
* return value.toUpperCase(); | |
* } | |
* }); // { fruit_apple: 'GREEN', fruit_orange: 'ORANGE', fruit_cherry: { color: 'RED' } } | |
*/ | |
function transformObj(obj, transforms = {}, level = 0) { | |
if (typeof obj !== 'object' || obj === null) { | |
// nothing we can do | |
return obj; | |
} | |
function convertValue(value) { | |
if (Array.isArray(value)) { | |
return value.map(convertValue); | |
} else if (typeof value === 'object') { | |
return transformObj(value, transforms, level + 1); | |
} else if (transforms.values) { | |
// transform value | |
return transforms.values(value, level); | |
} else { | |
return value; | |
} | |
} | |
return Object.keys(obj).reduce((result, key) => { | |
let value = obj[key]; | |
if (transforms.keys) { | |
// transform key | |
key = transforms.keys(key, level); | |
} | |
result[key] = convertValue(value); | |
return result; | |
}, {}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment