4 Ways to Safely Access Nested Objects in Vanilla Javascript
Thu Mar 18 2021 15:05:49 GMT+0000 (Coordinated Universal Time)
Saved by
@brunomgmateus
#javascript
// Example object
const macAyres = {
tours: {
nearMe: {
sanFrancisco: {
date: 'Sun Oct 27',
location: 'The Regency Ballroom',
cost: '30.00',
},
},
}
}
// 1. Ternary Operator to Check for null/undefined
const concertLocation = (macAyres.tours &&
macAyres.tours.nearMe &&
macAyres.tours.nearMe.sanJose)
? macAyres.tours.nearMe.sanJose.location
: undefined;
// 2. Oliver Steele’s Nested Object Access Pattern
const concertLocation = (macAyres.tours.nearMe.sanJose || {}).location;
/* Explanation:
As the || operator breaks return the truthy value encountered, the above expression would return macAyres.tours.nearMe.sanJose if it is not null/undefined, otherwise {}.
In this case, we will be accessing location from an empty object, and not from undefined, so we will avoid getting the error.
*/
// 3. Array Reduce
const paths = ['tours', 'nearMe', 'sanJose', 'location'];
const location = paths.reduce((object, path) => {
return (object || {})[path]; // Oliver Steele's pattern
}, macAyres)
// 4. Try/Catch Helper Function With ES6 Arrow Function
function getSafe(fn, defaultVal) {
try {
return fn();
} catch (e) {
return defaultVal;
}
}
// use it like this
getSafe(() => obj.a.lot.of.properties);
// or add an optional default value
getSafe(() => obj.a.lot.of.properties, 'nothing');
content_copyCOPY
Really usefull, specially when working with Vue / React / Angular in large API's, or with dynamic data.
https://betterprogramming.pub/4-ways-to-safely-access-nested-objects-in-vanilla-javascript-8671d09348a8
Comments