Skip to content

Instantly share code, notes, and snippets.

@ilearnio
Last active September 18, 2018 15:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ilearnio/e092b678a59427696edae7cc764ca9cf to your computer and use it in GitHub Desktop.
Save ilearnio/e092b678a59427696edae7cc764ca9cf to your computer and use it in GitHub Desktop.
const typeOf = require('just-typeof')
/**
* Update object values recursively
* @param {Object} obj
* @param {Function} handler
* @returns {Object} - new object
*/
const updateObjectValuesRecursively = (obj, handler) => {
const newObj = {}
Object.keys(obj).forEach(key => {
if (typeOf(obj[key]) === 'object') {
newObj[key] = updateObjectValuesRecursively(obj[key], handler)
} else {
newObj[key] = handler(obj[key])
}
})
return newObj
}
const obj = {
a: 1,
b: 'foo',
c: {
d: { e: 5 }
}
}
const newObj = updateObjectValuesRecursively(obj, val => {
if (typeof val === 'number') {
return val * 10
}
return val
})
newObj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment