Skip to content Skip to sidebar Skip to footer

Lodash , Check If Object Exists And Property Exists And Is True

Good morning . I need help on checking if object exists and certain propertie have value of true. Ex: validations={ 'DSP_INDICADOR': { 'required': true }, 'EMPRESA': {

Solution 1:

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']; //invalidconsole.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));
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

Solution 2:

I guess this would be it.

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

Post a Comment for "Lodash , Check If Object Exists And Property Exists And Is True"