Null-safe property access (and conditional assignment) in ES6/2015

后端 未结 10 1065
[愿得一人]
[愿得一人] 2020-11-22 13:00

Is there a null-safe property access (null propagation / existence) operator in ES6 (ES2015/JavaScript.next/Harmony) like ?. in

10条回答
  •  北海茫月
    2020-11-22 13:42

    A safe deep get method seems like a natural fit for underscore.js but there the issue is avoiding string programming. Modifying @Felipe's answer to avoid string programming (or at least pushes edge cases back to the caller):

    function safeGet(obj, props) {
       return (props.length==1) ? obj[keys[0]] :safeGet(obj[props[0]], props.slice(1))
    }
    

    Example:

    var test = { 
      a: { 
        b: 'b property value',
        c: { }
      } 
    }
    safeGet(test, ['a', 'b']) 
    safeGet(test, "a.b".split('.'))  
    

提交回复
热议问题