Note that there are some explanatory texts on larger screens.

plurals
  1. POBlocking the event loop with for..in
    primarykey
    data
    text
    <p>I would like to check a Javascript Object for unwanted properties with a schema definition for revalidator (<a href="https://github.com/flatiron/revalidator" rel="nofollow">https://github.com/flatiron/revalidator</a>).</p> <p>I came up with following snippet:</p> <pre><code>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; } </code></pre> <p>This code copies the wanted properties and loops synchronously over the schema recursing into nested schemas.</p> <p>I'm worried about blocking the event loop in this time.</p> <p>Is this negligible as I'm not doing I/O?</p> <p><strong>EDIT</strong></p> <p>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:</p> <pre><code>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 &amp;&amp; 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); }); } </code></pre> <p>This looks really messy, but it works and passes the tests. What do you think about this solution?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload