Check if object member exists in nested object

后端 未结 8 919
花落未央
花落未央 2020-11-27 05:00

Is there a simpler way than using ___ in object to check the existence of each level of an object to check the existence of a single member?

More conci

8条回答
  •  有刺的猬
    2020-11-27 05:29

    If you can use lodash library, it has a very elegant solution, hasIn.

    _.hasIn(someObject, 'member.level1.level2.level3');
    

    for example,

    var obj = {'x': 999, 'a': {'b': {'c': 123, 'd': 234}}}
    // => undefined
    
    _.hasIn(obj, 'x')
    // => true
    
    _.hasIn(obj, 'a.b.d')
    // => true
    
    _.hasIn(obj, 'a.b.e')
    // => false
    

提交回复
热议问题