Last active
November 1, 2018 16:17
-
-
Save marutypes/2c8b83e3c3248604433b4346e47ad056 to your computer and use it in GitHub Desktop.
set
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
// assuming keypath is string | number array like `['foo', 0, 'bar']` | |
export function set(object, keypath, value) { | |
if (keypath.length === 0) { | |
return value; | |
} | |
const segments = keypath.slice(0, -1); | |
const finalSegment = keypath.slice(-1)[0]; | |
const leaf = segments.reduce((node, key) => { | |
if (node[key]) { | |
return node[key]; | |
} | |
node[key] = {}; | |
return node[key]; | |
}, object); | |
leaf[finalSegment] = value; | |
return object; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment