🎄 Get 50% off from our JavaScript course for the holidays! 🎄
How to Safely Access Deeply Nested Properties in JavaScript

How to Safely Access Deeply Nested Properties in JavaScript

Ferenc Almasi • 🔄 2020 August 12 • 📖 1 min read

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

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
Copied to clipboard!

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.

// If `dateOfBirth` is undefined, `birthYear` will be undefined as well
const birthYear = user.dateOfBirth?.year;
optional-chaining.js
Copied to clipboard!
How to Safely Access Deeply Nested Properties in JavaScript
If you would like to see more Webtips, follow @flowforfrank
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
JavaScript Course

Resource

JavaScript Course Dashboard

Tired of looking for tutorials?

You are not alone. Webtips has more than 400 tutorials which would take roughly 75 hours to read.

Check out our interactive course to master JavaScript in less time.

Learn More

Recommended

🎉 Thank you for subscribing to our newsletter. x