Created
January 12, 2012 19:04
-
-
Save reissbaker/1602419 to your computer and use it in GitHub Desktop.
key selection, remapping
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var selectKeys = function(hash, keys) { | |
var output, prop, index; | |
output = {}; | |
if(!keys) return {}; | |
if(keys instanceof Array) { | |
for(index = 0; index < keys.length; index++) { | |
output[keys[index]] = hash[keys[index]]; | |
} | |
return output; | |
} | |
for(prop in keys) { | |
if(keys.hasOwnProperty(prop)) { | |
if(typeof keys[prop] === 'boolean') { | |
if(keys[prop]) output[prop] = hash[prop]; | |
// if false, don't copy the property | |
} else { | |
output[keys[prop]] = hash[prop]; | |
} | |
} | |
} | |
return output; | |
}; |
Line 4 you can use if (!keys)
instead of checking for undefined. That will catch null
too.
Nice. Changed it. That's a win for compression, too, since typestrings can't be compressed but variable names can.
Line 1 has a syntax error. You can drop the selectKeys:
.
var selectKeys = selectKeys: function(hash, keys) {
That's what I get for copying+pasting out of an object literal.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yep. Good point. Renaming it to
selectKeys
, made it select (and not remap) keys if given an array, and if given an object can remap them.