Mapping an array of objects to key/value pairs in CoffeeScript

var arr = [{name: 'a', value: 'b', other: 'c'}, {name: 'd', value: 'e', other: 'f'}];

var obj = arr.reduce(function ( total, current ) {
    total[ current.name ] = current.value;
    return total;
}, {});

Pure javascript. It’s practically a one liner, and it looks hawt.

Array.prototype.reduce is ES5, but isn’t difficult to shim. Here’s an example shim:

Array.prototype.reduce = function ( fun, initVal ) {
    var sum = initVal || this[ 0 ],
        i = 1, len = this.length;

    do {
        sum = fun.call( undefined, sum, this[i], i, this );
    } while ( ++i < len );

    return sum;
};

arr.reduce is a sophisticated version of arr.map, which is a sophisticated version of arr.forEach. You can do this for the same effect:

var obj = {};
arr.forEach(function ( val ) {
    obj[ val.name ] = val.value;
});

//and using jQuery.each
var obj = {};
$.each( arr, function ( index, val ) {
    obj[ val.name ] = val.value;
});

//latter version in coffeescript:
obj = {}
$.each( arr, (index, val) ->
    obj[ val.name ] = val.value
)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)