Last active
June 15, 2023 12:13
-
-
Save magicsk/ad5d3ca15e0b37ad96fc1d7b65e7179d to your computer and use it in GitHub Desktop.
set object property by string path TypeScript
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
const setObjectPropertyByPath = (object: any, path: string, value: any) => { | |
const parts = path.split('.') | |
const limit = parts.length - 1 | |
parts | |
for (let i = 0; i < limit; ++i) { | |
const key = parts[i] | |
if (parts?.[i + 1] === '0') { | |
value.map((nesttedValue: any, index: number) => { | |
setObjectPropertyByPath(object[key][index], parts.slice(i + 2).join('.'), nesttedValue) | |
}) | |
return | |
} | |
object = object[key] ?? (object[key] = {}) | |
} | |
const key = parts[limit] | |
object[key] = value | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment