0

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

Leonel Matias Domingos
  • 1,922
  • 5
  • 29
  • 53

2 Answers2

9

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>
Koushik Chatterjee
  • 4,106
  • 3
  • 18
  • 32
1

I guess this would be it.

if (validations["EMPRESA"] && validations["EMPRESA"].required) {
  console.log(true)
} else {
  console.log(false)
}
Vipin Kumar
  • 6,441
  • 1
  • 19
  • 25