[Javascript Crocks] Safely Access Nested Object Properties with `propPath`

In this lesson, we’ll look at the propPath utility function. We’ll ask for a property multiple levels deep in an object and get back a Maybe. We’ll get a Just when the property exists at our path and a Nothing if any part of the path is undefined.

 

const propPath = require('crocks/Maybe/propPath')

const user = {
    username: 'tester',
    email: 'test@gmail.com',
    address: {
        street: '111 E. West St',
        city: 'Anywhere',
        state: 'PA',
        postalCode: '19123-4567'
    }
};

const getPostalCode = propPath(['address', 'postalCode']);
const zip = getPostalCode(user).option('not available');

console.log(zip) //'19123-4567'

 

posted @ 2018-05-11 20:18  Zhentiw  阅读(207)  评论(0编辑  收藏  举报