I wonder how to use some reduce
logic over an object rather than an array. Something like iterating over tuples represented by
[ object_property, property_value ]
).
I tried some code like
var obj = { foo: 'bar', bar: 'baz' };
Array.prototype.reduce.call(obj, function(prev, val) {
console.log('new iteration');
// whatever code ...
return prev;
}, []);
but it doesn't perform any iteration. I can't understand why.
Maybe because the object properties are not enumerable?
Is there any way to run a reduce function on an object?
Note: There is no specific final purpose; I am exploring what's possible or what might be better patterns.
Array methods like reduce()
can only operate on arrays or array-like objects (with length
and numeric properties).
You can call Object.values()
to get an array of an object's property values.