Skip to content

Instantly share code, notes, and snippets.

@magicsk
Last active June 15, 2023 12:13
Show Gist options
  • Save magicsk/ad5d3ca15e0b37ad96fc1d7b65e7179d to your computer and use it in GitHub Desktop.
Save magicsk/ad5d3ca15e0b37ad96fc1d7b65e7179d to your computer and use it in GitHub Desktop.
set object property by string path TypeScript
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