Last active
October 19, 2020 22:43
-
-
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
This file contains 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
/** | |
* 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