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

时间:2018-12-06 20:39:36

标签: javascript json object data-structures lodash

例如,

检查此类对象中是否存在Response: { "version": "1.0", "response": { "directives": [ { "type": "Dialog.Delegate", "updatedIntent": { "name": "HobbyIntent", "confirmationStatus": "NONE", "slots": { "hobbyType": { "name": "hobbyType", "value": "general", "resolutions": { "resolutionsPerAuthority": [ { "authority": "amzn1.er-authority.echo-sdk.amzn1.ask.skill.a0b76b45-13ff-4be6-aff3-5b9bf60068d1.hobbieType", "status": { "code": "ER_SUCCESS_MATCH" }, "values": [ { "value": { "name": "general", "id": "958153f1b8b96ec4c4eb2147429105d9" } } ] } ] }, "confirmationStatus": "NONE", "source": "USER" }, "hobbyLocation": { "name": "hobbyLocation", "value": "indoors", "resolutions": { "resolutionsPerAuthority": [ { "authority": "amzn1.er-authority.echo-sdk.amzn1.ask.skill.a0b76b45-13ff-4be6-aff3-5b9bf60068d1.hobbyLocation", "status": { "code": "ER_SUCCESS_MATCH" }, "values": [ { "value": { "name": "indoor", "id": "b276393840653779e270ecb76ba4db12" } } ] } ] }, "confirmationStatus": "NONE", "source": "USER" } } } } ] }, "userAgent": "ask-node/2.3.0 Node/v8.10.0", "sessionAttributes": {} } Request ID: "eafe99b7-f994-11e8-8fcf-dfe94cfc1e14" Function Logs: START RequestId: eafe99b7-f994-11e8-8fcf-dfe94cfc1e14 Version: $LATEST 2018-12-06T20:24:23.009Z eafe99b7-f994-11e8-8fcf-dfe94cfc1e14 Current dialog state before switchesIN_PROGRESS END RequestId: eafe99b7-f994-11e8-8fcf-dfe94cfc1e14 REPORT RequestId: eafe99b7-f994-11e8-8fcf-dfe94cfc1e14 Duration: 95.26 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 21 MB 方法。

isCourage()

Lodash可以解决问题,但我不确定应该使用哪种方法。

2 个答案:

答案 0 :(得分:2)

使用lodash时,您可以使用一些功能:

您可以将_.isFunction_.get结合使用:

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>

您也可以使用_.result来立即获取值,而实际上使用not care则可以获取值。 _.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>

答案 1 :(得分:0)

您可以使用

_.get(puppy,'bar.goldenRetrieve.foo.hasCorauge.constructor') === 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>