Skip to content

Instantly share code, notes, and snippets.

@joaocarmo
Created July 1, 2019 11:19
Show Gist options
  • Save joaocarmo/daeed4dea230a3bb32b6fd27558c3bc4 to your computer and use it in GitHub Desktop.
Save joaocarmo/daeed4dea230a3bb32b6fd27558c3bc4 to your computer and use it in GitHub Desktop.
Set an object's nested value
/*
Usage: setNestedValue(<object>, <array>, <value>)
const object = {
key1: {
key11: 'nested-value'
}
}
const newObject = setNestedValue(object, ['key1', 'key12'], 'another-nested-value')
console.log(newObject)
> {
key1: {
key11: 'nested-value',
key12: 'another-nested-value'
}
}
*/
const setNestedValue = (object, pathArr, value) => {
if (typeof object === 'object') {
const obj = JSON.parse(JSON.stringify(object))
if (Array.isArray(pathArr)) {
const path = pathArr.slice(0)
const firstKey = path.shift()
if (!path.length) {
obj[firstKey] = value
} else {
if (typeof obj[firstKey] === 'undefined') {
obj[firstKey] = {}
}
obj[firstKey] = setNestedValue(obj[firstKey], path, value)
}
}
return obj
}
return object
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment