javascript Lodash,检查对象是否存在,属性是否存在且为真
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47885165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Lodash , check if object exists and property exists and is true
提问by Leonel Matias Domingos
Good morning . I need help on checking if object exists and certain propertie have value of true. Ex:
早上好 。我需要帮助检查对象是否存在并且某些属性的值为 true。前任:
validations={
"DSP_INDICADOR": {
"required": true
},
"EMPRESA": {
"required": true
},
.....
"NOME_AVAL": {
"required": false,
"notEqualToField": "NOME"
}
}
and then check for required:true
然后检查 required:true
Thanks in advance
提前致谢
回答by Koushik Chatterjee
How about simply using
简单地使用怎么样
_.get(validations, "EMPRESA.required");in lodash
_.get(validations, "EMPRESA.required");在洛达什
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 _.getin a more programmatic way with a default value (if the path not exist) and a arrayof keysin 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 Ndepth lookup path is not a string)
您可以_.get以更具编程性的方式使用它,并使用默认值(如果路径不存在)和以正确顺序进行查找的arrayof keys。因此,动态地您可以传递键数组来获取值,并且您不需要为由.like连接的字符串创建一个字符串"EMPRESA.required"(如果您的N深度查找路径输入不是 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>
回答by Vipin Kumar
I guess this would be it.
我想就是这样了。
if (validations["EMPRESA"] && validations["EMPRESA"].required) {
console.log(true)
} else {
console.log(false)
}

