1const getNestedObject = (nestedObj, pathArr) => {
2 return pathArr.reduce((obj, key) =>
3 (obj && obj[key] !== 'undefined') ? obj[key] : undefined, nestedObj);
4}
5
6// pass in your object structure as array elements
7const name = getNestedObject(user, ['personalInfo', 'name']);
8
9// to access nested array, just pass in array index as an element the path array.
10const city = getNestedObject(user, ['personalInfo', 'addresses', 0, 'city']);
11// this will return the city from the first address item.
12