Let's say I have a dictionary like this (this is just example data):
obj = {
name: 'John',
properties: {
age: 42,
address: 'somewhere'
}
}
What if I wanted to modify a value of any depth, specified by a variable?
For depth 1 it would be direct:
obj[what_to_modify] = new_value
but for depth > 1?
what_to_modify="properties.age"
obj[what_to_modify.split('.')] = new_value
// I KNOW, THIS DOESN'T WORK, IT JUST
// ILLUSTRATES WHAT I WANT TO ACHIEVE
My solution was to do a foor lop like this:
let levels = what_to_modify.split('.')
let it = obj
for(let k=0; k < levels.length; k++){
let key = levels[k]
if(k == levels.length -1){
it[key] = new_value
}else{
it = it[key]
}
}
This already works, but I wanted to know: Is there a less messy way to do it?
To be clear, I don't want to just read the value, I want to modify it, so Accessing nested JavaScript objects and arrays by string path and Access property via it's keyPath in Javascript? don't solve my problem
IMPORTANT
The accepted answer uses lodash, but actually I shouldn't include new dependencies in my project, so if there's any other way with vanilla JS, I will change the accepted answer to that.