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
  • 相关阅读:
    VUE 脚手架模板搭建
    defineProperty
    理解JS中的call、apply、bind方法
    Two-phase Termination模式
    打印样式设计
    浏览器内部工作原理
    Immutable Object模式
    怎么跳出MySQL的10个大坑
    控制台console
    整理的Java资源
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6569417.html
Copyright © 2011-2022 走看看