Ce n'est pas très difficile à mettre en œuvre vous-même:
function reduceObj(obj, callback, initial) {
"use strict";
var key, lastvalue, firstIteration = true;
if (typeof callback !== 'function') {
throw new TypeError(callback + 'is not a function');
}
if (arguments.length > 2) {
firstIteration = false;
lastvalue = initial;
}
for (key in obj) {
if (!obj.hasOwnProperty(key)) continue;
if (firstIteration)
firstIteration = false;
lastvalue = obj[key];
continue;
}
lastvalue = callback(lastvalue, obj[key], key, obj);
}
if (firstIteration) {
throw new TypeError('Reduce of empty object with no initial value');
}
return lastvalue;
}
En action:
var o = {a: {value:1}, b: {value:2}, c: {value:3}};
reduceObj(o, function(prev, curr) { prev.value += cur.value; return prev;}, {value:0});
reduceObj(o, function(prev, curr) { return {value: prev.value + curr.value};});
reduceObj(o, function(prev, curr) { return prev + curr.value; }, 0);
Vous pouvez également l'ajouter au prototype Object:
if (typeof Object.prototype.reduce !== 'function') {
Object.prototype.reduce = function(callback, initial) {
"use strict";
var args = Array.prototype.slice(arguments);
args.unshift(this);
return reduceObj.apply(null, args);
}
}
Underscore.js
?