资讯详情

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

In this lesson we'll see how Ramda'spathandpathOrfunctions can be used to safely access a deeply nested property from an object while avoiding the dreaded checks forundefinedat 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

标签: lumberg连接器wrkmv

锐单商城拥有海量元器件数据手册IC替代型号,打造 电子元器件IC百科大全!

锐单商城 - 一站式电子元器件采购平台