I would like to check a Javascript Object for unwanted properties with a schema definition for revalidator (https://github.com/flatiron/revalidator).
I came up with following snippet:
function strip(object, schema) {
var strippedObject = {};
for (var property in schema.properties) {
if (schema.properties[property].type === 'object') {
strippedObject[property] = strip(object[property], schema.properties[property]);
} else {
strippedObject[property] = object[property];
}
}
return strippedObject;
}
This code copies the wanted properties and loops synchronously over the schema recursing into nested schemas.
I'm worried about blocking the event loop in this time.
Is this negligible as I'm not doing I/O?
EDIT
Thanks for the comments. Like jbaylina mentioned it is indeed the case that the schema is nested to a maximum of 2 levels with maybe around 10 properties each. Nevertheless I tried out using setImmediate an it works, but I would maybe iterate asynchronously when it really is a problem:
function strip(object, schema, callback) {
var strippedObject = {};
async.each(Object.keys(schema.properties), function (property, next) {
if (schema.properties.hasOwnProperty(property)) {
if (schema.properties[property].type && schema.properties[property].type === 'object') {
strip(object[property], schema.properties[property], function (err, obj) {
if (err) return next(err);
strippedObject[property] = obj;
next();
});
} else {
strippedObject[property] = object[property];
next();
}
}
}, function (err) {
if (err) return callback(err);
return callback(null, strippedObject);
});
}
This looks really messy, but it works and passes the tests. What do you think about this solution?