I'd like to remove certain members of an object (for the sake of argument, those whose keys start with '_'). What's an elegant way to do this? The naïve way would be:
for (var i in obj)
if (i[0] === '_')
delete obj[i];
but that modifies the underlying object during the iteration. In Node at least I guess I could
Object.keys(obj).forEach(function (i) { if (i[0] === '_') delete obj[i]; });
or restart the iteration each time something's deleted with an awkward nested loop.
Are there any better solutions?
EDIT: In testing just now, in node.js at least, the naïve solution actually seems to work. It certainly is possible that for...in is (required to be) implemented safely. Anyone know?
You do not need to worry about it. An excerpt for ECMAScript Language Specification §12.6.4 explicitly states (emphasised by me):
The mechanics and order of enumerating the properties (step 6.a in the first algorithm, step 7.a in the second) is not specified. Properties of the object being enumerated may be deleted during enumeration. If a property that has not yet been visited during enumeration is deleted, then it will not be visited. If new properties are added to the object being enumerated during enumeration, the newly added properties are not guaranteed to be visited in the active enumeration. A property name must not be visited more than once in any enumeration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With