Last active
August 20, 2019 15:48
-
-
Save markmichon/8c1538d3f18b85301dbc3d10cf0606ba to your computer and use it in GitHub Desktop.
Modify values in an object recursively
This file contains hidden or 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
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