我正在编写一个从广告平台获取一些数据的应用程序。我的数据结构如下:
{
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操作的最佳方法是什么?
感谢。
答案 0 :(得分:3)
一种可能的方法:
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
方法并使用单个缩减来完成收集,如下所示:
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
});
});