Let's assume that you have the following object:
javascriptlet obj = { 'name': 'Erik', 'age': 30, 'location': { 'city': 'Barcelona' }, 'height': 177, 'weight': 72 }
If you want to define a variable (or a path) to access to a property dynamically:
javascriptlet path = 'location.city';
You can get the value using the reduce()
function:
javascriptlet val = path.split('.').reduce((ref, prop) => ref = ref?.[prop], obj); // 'Barcelona'
You can get the reference to the last key using the reduce()
function:
javascriptlet key = path.split('.').slice(0, -1).reduce((ref, prop) => ref = ref?.[prop], obj); // obj['location']
At this point, let's assume that you want to modify the current value:
javascript// You can get the last prop as path.split('.').pop() => 'city' // The following line is equivalent to obj['location']['city'] key[path.split('.').pop()] = 'Madrid';
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.