I'm somewhat curious on peoples opinion about such a method. I Actually didn't find anything similar in librarys I use on regular bases so far.
This is my implementation:
Object.map = function _map( obj, transform ) {
if( typeof obj === 'object' && typeof transform === 'function' ) {
Object.keys( obj ).forEach(function _forEach( key ) {
(function _mapping( oldkey, transmuted ) {
if( transmuted && transmuted.length ) {
obj[ transmuted[ 0 ] || oldkey ] = transmuted[ 1 ];
if( transmuted[ 0 ] && oldkey !== transmuted[ 0 ] ) {
delete obj[ oldkey ];
}
}
}( key, transform.apply( obj, [ key, obj[ key ]] ) ));
});
}
};
I normally put it on the Object object and not the prototype. However, usage is like this
var foo = {
someProp: 5,
bar: 10,
moar: 20
};
Object.map( foo, function(key, value) {
return [ key.toUpperCase(), value*2 ];
});
result:
Object { SOMEPROP=10, BAR=20, MOAR=40}
I most often use it to translate CSS properties (to vendor prefixes). But I don't see people use an approach like this often in ECMAscript. Any thoughts?
jQuery.each()does exactly that. \$\endgroup\$