Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good idiom to filter out members of an object (javascript)

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?

like image 755
Grumdrig Avatar asked Jan 08 '12 16:01

Grumdrig


1 Answers

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.

like image 200
OnTheFly Avatar answered Oct 01 '22 22:10

OnTheFly