The underscore filter method will work on the object used as a hash or dictionary, but it will return an array of enumerated values of the object and cross out the keys. I need a function to filter a hash by its values, which would preserve keys, and write this in Coffeescript:
hash_filter: (hash, test_function) -> keys = Object.keys hash filtered = {} for key in keys filtered[key] = hash[key] if test_function hash[key] filtered
If you are not using Coffeescript, here the compiled result in Javascript has cleared a bit:
hash_filter = function(hash, test_function) { var filtered, key, keys, i; keys = Object.keys(hash); filtered = {}; for (i = 0; i < keys.length; i++) { key = keys[i]; if (test_function(hash[key])) { filtered[key] = hash[key]; } } return filtered; } hash = {a: 1, b: 2, c: 3}; console.log((hash_filter(hash, function(item){return item > 1;})));
TL; DR: Object.keys () is great!
Pathogen
source share