marcandrewb
2/12/2018 - 4:35 PM

Using Array reduce to safely access nested objects.

Using Array reduce to safely access nested objects.

const user = {
  personalInfo: {
    name: 'Michael Bluth',
    addresses: [{ city: 'Sudden Valley' }]
  }
};

const getNestedObject = (nestedObj, pathArr) => {
  return pathArr.reduce(
    (obj, key) => (obj && obj[key] !== 'undefined' ? obj[key] : null),
    nestedObj
  );
};

// pass in your object structure as array of strings
const name = getNestedObject(user, ['personalInfo', 'name']);

// to access nested array, just pass in array index as an element the path array.
const city = getNestedObject(user, ['personalInfo', 'addresses', 0, 'city']);

// this will return the city from the first address item.