Skip to content

Instantly share code, notes, and snippets.

@kitsune7
Last active July 3, 2019 01:02
Show Gist options
  • Save kitsune7/09116e302ec56126f0b6a198eba7d67a to your computer and use it in GitHub Desktop.
Save kitsune7/09116e302ec56126f0b6a198eba7d67a to your computer and use it in GitHub Desktop.
A way to recursively get or set a property dynamically at any level within an object.
const getObjectProperty = (object, properties) => {
return properties.length === 0 ? object : getObjectProperty(object[properties[0]], properties.slice(1))
}
const setObjectProperty = (object, properties, value) => {
if (properties.length === 1) {
object[properties[0]] = value
}
getObjectProperty(object, properties.slice(0, properties.length - 1))[properties[properties.length - 1]] = value
}
// Working example
const example = { a: { b: { c: [ { d: 1 } ] } } }
console.log('Before:', getObjectProperty(example, ['a', 'b', 'c', 0, 'd']))
setObjectProperty(example, ['a', 'b', 'c', 0, 'd'], 0) // Changes example.a.b.c[0].d from 1 to 0
console.log('After:', getObjectProperty(example, ['a', 'b', 'c', 0, 'd']))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment