Lodash , check if object exists and property exists and is true

假如想象 提交于 2019-12-13 03:46:30

问题


Good morning . I need help on checking if object exists and certain propertie have value of true. Ex:

validations={
  "DSP_INDICADOR": {
    "required": true
  },
  "EMPRESA": {
    "required": true
  },
.....
  "NOME_AVAL": {
    "required": false,
    "notEqualToField": "NOME"
  }
}

and then check for required:true

Thanks in advance


回答1:


I guess this would be it.

if (validations["EMPRESA"] && validations["EMPRESA"].required) {
  console.log(true)
} else {
  console.log(false)
}



回答2:


How about simply using

_.get(validations, "EMPRESA.required"); in lodash

In this way we can fetch upto any depth, and we don't need to assure with consecutive && again and again that the immediate parent level exists first for each child level.

You can use this _.get in a more programmatic way with a default value (if the path not exist) and a array of keys in proper sequence for lookup. So, dynamically you can pass array of keys to fetch values and you don't need to create a string for that joined by . like "EMPRESA.required" (in the case your input for N depth lookup path is not a string)

Here is an example:

let obj = {a1: {a2: {a3: {a4: {a5: {value: 101}}}}}};

let path1 = ['a1', 'a2', 'a3', 'a4', 'a5', 'value'], //valid
    path2 = ['a1', 'a2', 'a3', 'a4'], //valid
    path3 = ['a1', 'a3', 'a2', 'x', 'y', 'z']; //invalid
    
console.log(`Lookup for ${path1.join('->')}: `, _.get(obj, path1));
console.log(`Lookup for ${path2.join('->')}: `, _.get(obj, path2));
console.log(`Lookup for ${path3.join('->')}: `, _.get(obj, path3));
console.log(`Lookup for ${path3.join('->')} with default Value: `, _.get(obj, path3, 404));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>


来源:https://stackoverflow.com/questions/47885165/lodash-check-if-object-exists-and-property-exists-and-is-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!