我正在编写一个从广告平台获取一些数据的应用程序。我的数据结构如下:
{
campaign_id: 123,
campaign_name: SomeName,
subcampaigns: [
{country: Australia, impressions: 12000, cost: 12},
{country: Australia, impressions: 14000, cost: 17},
{country: Singapore, impressions: 10000, cost: 7},
{country: Singapore, impressions: 7000, cost: 6}
]
}
我需要把它变成这样:
[{
campaign_name: SomeName,
country: Australia,
impressions: 36000
cost: 29
},
{
campaign_name: SomeName,
country: Singapore
impressions: 17000
cost: 13
}]
在NodeJS中执行这种Map Reduce操作的最佳方式是什么?
谢谢。
一种可能的方法:
var groupedSubcampaigns = _.groupBy(data.subcampaigns, 'country');
var summator = function(memo, el) {
return memo + el;
};
var result = _.map(groupedSubcampaigns, function(group, country) {
return {
campaign_name: data.campaign_name,
country: country,
impressions: _.reduce(_.pluck(group, 'impressions'), summator, 0),
cost: _.reduce(_.pluck(group, 'cost'), summator, 0)
}
});
console.log(result);
Demo(不知何故,很难找到一个带有包含外部库选项的node.js在线代码板,但我想jsfiddle在这种情况下会很好地工作)
解释。。。好吧,我相信这里的代码很能自我解释。)首先,我们创建了一个按国家分组的子竞争的散列,然后我们用_.map
遍历该散列的每个项,用"summator"函数减少其impressions
和cost
属性。
尽管如此,仍有改进的空间:您可以放弃pluck
方法,只需进行一次reduce即可完成集合,如下所示:
var summator = function(memo, el) {
memo.impressions += el.impressions;
memo.cost += el.cost;
return memo;
};
var result = _.map(groupedSubcampaigns, function(group, country) {
var aggregateObj = _.reduce(group, summator, {impressions:0, cost:0});
return _.extend(aggregateObj, {
campaign_name: data.campaign_name,
country: country
});
});
演示。