0

So I have this function to check several "paths" in an objects for a property to exist and to be "truthy".

function validate(obj, ...paths) {
    let missing = [];
    for (let path of paths) {
        let pathPieces = path.split('.');
        let testing = obj;
        for (let pathPart of pathPieces) {
            let propertyName = pathPart;
            let isArrayNotation = pathPart.indexOf("[") > -1;
            let arrayNotationPieces = pathPart.split('[');
            if(isArrayNotation) 
            {
              propertyName = arrayNotationPieces[0];
            }
            if (!testing[propertyName]) {
                missing.push(path);
                break;
            }
            if(isArrayNotation) 
            {
                if(Array.isArray(testing[propertyName])) {
                    let elementIndexToCheck = parseInt(arrayNotationPieces[1]);
                    testing = testing[propertyName][elementIndexToCheck]
                    if(!testing) break;    
                } else {
                    missing.push(path);
                }
                
            } else {
                testing = testing[propertyName];
            }
        }
    }
    return missing;
}
const obj = {
    "path": "/organizations",
    "method": {
        "value": "POST",
        "level3": {
            level4: {
                level5: true
            }
        },
        "items": [
            "POST"
        ]
    },
    "body": {
        "organization_name": "cloud 9 to be deleted"
    }
};
let result = validate(obj, "patH", "method.value", "method.level3.level4.level5", "method.items[2]");
console.log(result);

While it seems to work as expected for simple properties, I wonder how I can check if arrays have a certain number of items.

For example:

let result = validate(obj, "path", "method.items[1]");

should return 1 element in missing array ["method.items"], because we have specified index 1 out of range.

And also there is a room for optimizing this thing, so I'd be happy to hear your advice.

kolodi
  • 1,002
  • 9
  • 16
  • 1
    what would you expect the test string to be? `let result = validate(obj, "items[0]")`? – jshawl Jun 10 '20 at 14:08
  • let result = validate(obj, "method.items[2]") => ["method.items"], just list the property obj["method"]["items"] as missing, because it has only 1 element and we have specified 2. – kolodi Jun 10 '20 at 14:12
  • Does this answer your question? [Check if array is empty or does not exist. JS](https://stackoverflow.com/questions/24403732/check-if-array-is-empty-or-does-not-exist-js) – Liam Jun 10 '20 at 14:43

0 Answers0