Created
July 1, 2019 11:19
-
-
Save joaocarmo/daeed4dea230a3bb32b6fd27558c3bc4 to your computer and use it in GitHub Desktop.
Set an object's nested value
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
/* | |
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