Reputation: 2040
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
Upvotes: 0
Views: 18489
Reputation: 4175
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>
Upvotes: 9
Reputation: 6546
I guess this would be it.
if (validations["EMPRESA"] && validations["EMPRESA"].required) {
console.log(true)
} else {
console.log(false)
}
Upvotes: 1