Skip to content

Instantly share code, notes, and snippets.

@iambriansreed
Last active October 19, 2020 22:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iambriansreed/2389c4bc822b9e2e8a0537b2c0ba99da to your computer and use it in GitHub Desktop.
Save iambriansreed/2389c4bc822b9e2e8a0537b2c0ba99da to your computer and use it in GitHub Desktop.
Sets the value at path of object. If a portion of path doesn't exist, it's created. An alternative to https://lodash.com/docs/#set
/**
* Sets the value at path of object. If a portion of path doesn't exist, it's created.
* An alternative to https://lodash.com/docs/#set
*
* @param {object} obj
* @param {string} keyPath
* @param {any} value
*/
export default function deepSet(
obj: { [key: string]: any },
keyPath: string,
value: any
) {
if (!keyPath.includes('.')) {
return { ...obj, [keyPath]: value };
}
if (keyPath.includes('.')) {
const keys = keyPath.split('.');
const pointers = [{ key: '', value: { ...obj } }];
for (let i = 1; i <= keys.length; i++) {
pointers.push({
key: keys[i - 1],
value: pointers[i - 1].value[keys[i - 1]],
});
}
pointers[pointers.length - 1].value = value;
for (let i = pointers.length - 2; i > -1; i--) {
pointers[i].value[pointers[i + 1].key] = pointers[i + 1].value;
}
return pointers[0].value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment