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

Resource
Remove ads📚 Get access to exclusive content
Want to get access to exclusive content? Support webtips with the price of a coffee to get access to tips, checklists, cheatsheets, and much more. ☕
Get access