Get Object Property Paths Safely In JavaScript
Getting object property paths can be tricky on complex objects, because just one property being empty will trigger an error. For example, when getting page menu data from an API:
function getPageMenu() { return [ { title: 'Dashboard', location: { fullUrl: 'https://my-website.com/dashboard/user1', shortUrl: 'https://goo.gl/929okH' } }, { title: 'Logout', // No location since it redirects to a login page } ] } function printAllPageLinks() { const pageMenuData = getPageMenu(); for (let page of pageMenuData) { // Error here console.log(page.location.fullUrl); } } printAllPageLinks();
There will be an error with the console.log above. Normally, these links would be used in a UI, but this is just for example purposes. To avoid this, the && syntax can be used:
function printAllPageLinks() { const pageMenuData = getPageMenu(); for (let page of pageMenuData) { console.log(page.title, page.location && page.location.fullUrl); } }
This is ok, but it is verbose and will look confusing to anyone not very familiar with Javascript as this syntax does not appear in any other very popular languages (that I am aware of). Instead, a get function can be used from Lodash (there are similar alternatives in many other utility libraries):
function printAllPageLinks() { const pageMenuData = getPageMenu(); for (let page of pageMenuData) { console.log(page.title, _.get(page, 'location.fullUrl')); } }
The processing will be slower due to the interpretation of the string properties, but that is the only drawback. For the most part this level of efficiency will not matter. Since the implentation for the above is complex (e.g. it should support arrays too), I will not be showing a simple example like usual.
Finally, there is a JavaScript feature proposal called Optional Chaining in the works for language syntax support. Just keep in mind it is early in the process being stage 1 and may never actually make it into the language:
function printAllPageLinks() { const pageMenuData = getPageMenu(); for (let page of pageMenuData) { console.log(page.title, page.?location.?fullUrl); } }
Github Location https://github.com/Jacob-Friesen/obscurejs/blob/master/2018/getValue.js



















