Skip to content

Instantly share code, notes, and snippets.

@marutypes
Last active November 1, 2018 16:17
Show Gist options
  • Save marutypes/2c8b83e3c3248604433b4346e47ad056 to your computer and use it in GitHub Desktop.
Save marutypes/2c8b83e3c3248604433b4346e47ad056 to your computer and use it in GitHub Desktop.
set
// 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