Skip to content

Instantly share code, notes, and snippets.

@markmichon
Last active August 20, 2019 15:48
Show Gist options
  • Save markmichon/8c1538d3f18b85301dbc3d10cf0606ba to your computer and use it in GitHub Desktop.
Save markmichon/8c1538d3f18b85301dbc3d10cf0606ba to your computer and use it in GitHub Desktop.
Modify values in an object recursively
function applyToKeys(obj, modify) {
let newObj = {}
for (let [key, value] of Object.entries(obj)) {
if (typeof value === 'object') {
newObj[key] = applyToKeys(obj[key], modify)
} else {
newObj[key] = modify(value)
}
}
return newObj
}
// Example
let test = {
x: 1,
y: 2,
z: {
a: 1,
b: 2,
}
}
let example = applyToKeys(test, function(value) {
return value + 1
})
// Expected result
// {
// x: 2,
// y: 3,
// z: {
// a: 2,
// b: 3,
// }
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment