简体   繁体   English

检查使用lodash嵌套的对象中是否存在方法

[英]Check if a method exists from an object nested using lodash

For example, 例如,

check if isCourage() method exist in such object. 检查isCourage()方法是否存在于该对象中。

puppy {

  ...

  goldenRetriever {

     ...

     hasCourage(){ ... }

  }

}

Lodash can do the trick but i'm not sure which method should i use. Lodash可以解决问题,但我不确定应该使用哪种方法。

With lodash you have a few functions that might be helpful to you: 使用lodash,您可以使用一些对您有所帮助的功能:

You can use _.isFunction with _.get : 您可以将_.isFunction_.get _.isFunction使用:

 let obj = { foo:{ bar:{ fooBar: function(b) { return b } } } } console.log(_.isFunction(_.get(obj,'foo.bar.fooBar'))) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script> 

You can also use _.result to get the value right away and not care really if it is or not a function. 您也可以使用_.result来立即获取值,而not care它是否是一个函数。 _.result would walk the path executing anything that is a function and return the final value: _.result会执行所有执行函数的路径,并返回最终值:

 let obj = { foo:{ bar:{ fooBar: function(b='yay') { return b } } } } console.log(_.result(obj, 'foo.bar.fooBar')) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script> 

You can use 您可以使用

_.get(puppy,'bar.goldenRetrieve.foo.hasCorauge.constructor') === Function

(bar and foo are examples since ... would be confusing and .contructor should return Function if it is a function...) (bar和foo是示例,因为...会造成混淆,如果是函数,.contructor应该返回Function。)

 let obj = { foo:{ bar:{ myFn:function(b){return b;} } } } console.log(_.get(obj,'foo.bar.myFn.constructor')===Function); console.log(_.get(obj,'foo.bar.myFn2.constructor')===Function); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM