DEV Community

Discussion on: Accessing Nested Objects in JavaScript

Collapse
 
alexkli profile image
Alexander Klimetschek

Here is a simpler self-contained helper function:

function resolve(obj, path) {
    return path.split('.').reduce((o, key) => o && o[key], obj);
}

resolve(user, 'personalInfo.name');
resolve(user, 'personalInfo.addresses.0.city');

Note the dot notation, also works for arrays with index addressing.