How to Safely Access Deeply Nested Properties in JavaScript

How to Safely Access Deeply Nested Properties in JavaScript

Ferenc AlmasiLast updated 2020 August 12 • Read time 1 min read
  • twitter
  • facebook
JavaScript

You can use the function below to get nested properties from objects error safe. If a property doesn’t exist, it won’t throw the famous last words: “cannot read property of undefined

Copied to clipboard! Playground
const getProperty = (obj, path) => (path.split('.').reduce((value, el) => value[el], obj));

const user = {
  settings: {
    theme: 'default'
  }
};

getProperty(user, 'settings.theme');       // This will return “default”
getProperty(user, 'settings.invalidPath'); // This will return `undefined`
get-nested-property.js

Keep in mind that this will return undefined if the property does not exist. If your properties can be undefined on purpose and you are specifically looking for that, you may run into issues.

If you are using Babel, you can also achieve the same thing by using the optional chaining plugin.

Copied to clipboard!
// If `dateOfBirth` is undefined, `birthYear` will be undefined as well
const birthYear = user.dateOfBirth?.year;
optional-chaining.js
How to Safely Access Deeply Nested Properties in JavaScript
If you would like to see more Webtips, follow @flowforfrank

Resource

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
📚 More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.