I recently had use for a map()-function while writing Javascript. Javascript has Array.map(), and jQuery has $.map(), but those only works on arrays, and I needed one that could do its magic on objects. So I wrote this one:
function mapObj(obj, fun) {
var ret = {};
for (i in obj) {
if (obj.hasOwnProperty(i)) {
fun.call({emit: function(key, value) {
ret[key] = value;
}}, i, obj[i]);
}
}
return ret;
}
mapObj() takes an object and a function, applies the function to each property of the object, gathers up the result and returns it as a new object. The function supplied to mapObj is called with two parameters, the key and value of the current property. To add properties to the final object, call this.emit(key, value) from the function. This may be called any number of times for each property (including zero).
Here’s a usage example:
var obj = {a:1, b:2, c:3, d:4};
var obj2 = mapObj(obj, function(key, val) {
if (val != 2) {
this.emit(key.toUpperCase(), val*2);
} else {
this.emit(key, val);
this.emit('aaa', 'bbb');
}
});
// {A:2, b:2, aaa:'bbb', C:6, D:8}
Maybe someone will find this useful.
My name is Arne Martin Aurlien. I run this thing. Here’s a few facts about me:
Here’s a few things I have made: