[Ramda] Get Deeply Nested Properties Safely with Ramda's path and pathOr Functions

In this lesson we'll see how Ramda's path and pathOr functions can be used to safely access a deeply nested property from an object while avoiding the dreaded checks for undefined at each new property in the desired path.

 

const R = require('ramda');
const {path, pathOr} = R;

const acctDept = {
    name: 'Accounts Payable',
    location: '14th floor',
    personnel: {
        manager: {
            fName: 'Bill',
            lName: 'Lumberg',
            title: 'director of stuff and things',
            salary: 75000
        }
    }
};

const itDept = {
    name: 'IT',
    location: 'remote',
    personnel: {}
};

// path: will return undefined if cannot find prop
const getMrgLastName = path(['personnel', 'manager', 'lName']);
const getMrgLastNameOrDefaultVal = pathOr('Nobody', ['personnel', 'manager', 'lName'])

const res = getMrgLastName(acctDept);
console.log("res:", res); // Lumberg
const res2 = getMrgLastName(itDept);
const res3 = getMrgLastNameOrDefaultVal(itDept);
console.log("res2:", res2); // undefined
console.log("res3:", res3); // Nobody

 

posted @ 2017-03-18 03:25  Zhentiw  阅读(271)  评论(0编辑  收藏  举报