-
-
Save markandrewj/66cf477684de853e06ce to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Universal mongodb reduce function for complex objects | |
// | |
// Example: | |
// | |
// emit({ total_views: 3, page_type: {home: 1, product: 2}, site_id: [1] }) | |
// emit({total_views: 5, page_type: {home: 1, collection: 4}, site_id: [2]}) | |
// | |
// -> reduce | |
// | |
// { total_views: 8, page_type: { home: 2, product: 2, collection: 4 }, site_id: [1,2] } | |
// | |
function(key, values){ | |
var result = {} | |
var merge_obj = function(from, to){ | |
for (key in from) { | |
if (Object.prototype.toString.call(from[key]) == "[object Object]") { | |
if (!to[key]) | |
to[key] = {} | |
merge_hash(from[key], to[key]) | |
} else if (Object.prototype.toString.call(from[key]) == "[object Array]") { | |
if (!to[key]) | |
to[key] = [] | |
to[key].push(from[key]) | |
} else { | |
if (!to[key]) | |
to[key] = 0 | |
to[key] += from[key] | |
} | |
} | |
} | |
values.forEach(function(value){ | |
merge_obj(value, result) | |
}) | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment