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.