documentcloud/underscore — Issue #487: Proposal: hash iterators
Author: dbrans
Created: 2012-02-21 01:53:54+00:00
State: open

This proposal concerns iteration over key-value pairs of a hash in JavaScript.

# _.eachHash
Works like _.each but reverses the order of first two arguments passed to iterator: [key, val] instead of [val, key].

Rationale: key, value is the natural order for iterating over hash entries. The following is a common js pattern:

```javascript
function set(key, value) {
if(_.isString(key)) {
// set the value
} else {
// allow multiple values to be set.
_.eachHash(key, set);
}
}
```

'Hash' versions of all underscore's collection functions could be based on _.eachHash and return a hash whenever an array is returned.

# _.mapHash
Works like _.map but returns an object. Iterator returns a [key, value] pair:

```javascript
_.mapHash = function(obj, iterator, context) {
var r = {}; _.eachHash(obj, function(key, val) {
var pair = iterator.call(context, key, val, obj);
r[pair[0]] = pair[1];
});
return r;
};

// Example: Convert all keys in a hash to lowercase.
function toLowerCaseHash (obj) {
return _.mapHash(obj, function(key, val) {
return [key.toLowerCase(), val];
});
}
```

# _.filterHash
Works like _.filter, but returns a hash.

### etc...
Let me know if I'm smoking hash.