使用Underscore JS对JSON数组进行分组和聚合

时间:2014-04-09 06:00:48

标签: javascript arrays json underscore.js

我有一个json数组对象。我想根据列“FlexCategoryName”对数据进行分组,并对矩阵列执行聚合,例如“成本”平均值,“点击”总和等。下面是JSON数组对象

Array[100]
0: Object
1: Object
2: Object
3: Object

0:对象

Clicks: 1067
Cost: 4094.2
Date: "2/8/2014"
FlexCategoryName: "Cat1"
Impressions: 65943
Leads: 20

VENUE_ID:1

1:对象

Clicks: 106
Cost: 409
Date: "2/8/2014"
FlexCategoryName: "Cat2"
Impressions: 65941
Leads: 21
VENUE_ID:1

2:对象

Clicks: 106
Cost: 409
Date: "2/8/2014"
FlexCategoryName: "Cat2"
Impressions: 10
Leads: 21
VENUE_ID:2

3:对象

Clicks: 106
Cost: 409
Date: "2/8/2014"
FlexCategoryName: "Cat3"
Impressions: 10
Leads: 21
VENUE_ID:2

4:对象

Clicks: 20
Cost: 10
Date: "2/8/2014"
FlexCategoryName: "Cat5"
Impressions: 10
Leads: 21
 VENUE_ID:3

如何使用Underscore JS对矩阵列执行分组和聚合。

预期产出

0: Object
Cost: sum of all cost based on FlexCategoryName Cat1
FlexCategoryName: "Cat1"
Impressions: sum of all Impressions based on FlexCategoryName Cat1

1: Object
Cost: sum of all cost based on FlexCategoryName Cat2
FlexCategoryName: "Cat2"
Impressions: sum of all Impressions based on FlexCategoryName Cat2

1 个答案:

答案 0 :(得分:27)

var _ = require("underscore");
function sum(numbers) {
    return _.reduce(numbers, function(result, current) {
        return result + parseFloat(current);
    }, 0);
}
var result = _.chain(data)
    .groupBy("FlexCategoryName")
    .map(function(value, key) {
        return {
            FlexCategoryName: key,
            Cost: sum(_.pluck(value, "Cost")),
            Impressions: sum(_.pluck(value, "Impressions"))
        }
    })
    .value();

console.log(result);

<强>输出

[ { FlexCategoryName: 'Cat1', Cost: 4094.2, Impressions: 65943 },
  { FlexCategoryName: 'Cat2', Cost: 818, Impressions: 65951 },
  { FlexCategoryName: 'Cat3', Cost: 409, Impressions: 10 },
  { FlexCategoryName: 'Cat5', Cost: 10, Impressions: 10 } ]

如果要查找平均值而不是求和,则只需更改函数。

修改:如果您想基于多个字段进行分组,可以像这样嵌套分组

var result = _.chain(data)
    .groupBy("FlexCategoryName")
    .map(function(value, key) {
        return _.chain(value)
            .groupBy("VENUE_ID")
            .map(function(value1, venue_id) {
                return {
                    FlexCategoryName: key,
                    Cost: sum(_.pluck(value1, "Cost")),
                    Impressions: sum(_.pluck(value1, "Impressions")),
                    VENUE_ID: venue_id
                }
            })
            .value();
    })
    .value();