锐单电子商城 , 一站式电子元器件采购平台!
  • 电话:400-990-0325

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

时间:2022-12-14 16:00:00 lumberg连接器wrkmv

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

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

相关文章