Access an object property using a string in JavaScript

Let's assume that you have the following object:

javascript
let 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:

javascript
let path = 'location.city';

Getting the value

You can get the value using the reduce() function:

javascript
let val = path.split('.').reduce((ref, prop) => ref = ref?.[prop], obj); // 'Barcelona'

Getting the key

You can get the reference to the last key using the reduce() function:

javascript
let 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.