zoukankan      html  css  js  c++  java
  • [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
  • 相关阅读:
    King's Quest
    Prince and Princess
    Strongly connected
    线性渐变--linear-gradient
    镜像渐变-radio-gradient
    宽度自适应-左右
    宽度自适应-左中右
    HTML5 视频规范简介
    SVG格式
    Html5新标签解释及用法
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6569417.html
Copyright © 2011-2022 走看看