下划线做一些计算并返回新对象

时间:2015-02-03 16:37:25

标签: javascript underscore.js time-series click-tracking

我有这样的时间序列:

[
    {
        "_id": {
            "action": "click",
            "date": "2015-02-02T00:00:00+01:00"
        },
        "total": 5
    },
    {
        "_id": {
            "action": "hit",
            "date": "2015-02-02T00:00:00+01:00"
        },
        "total": 13
    },
    {
        "_id": {
            "action": "hit",
            "date": "2015-02-03T00:00:00+01:00"
        },
        "total": 25
    },
    {
        "_id": {
            "action": "click",
            "date": "2015-02-03T00:00:00+01:00"
        },
        "total": 7
    }
]

我需要做一些计算并返回一个类似的对象,特别是,我需要找到点击和点击之间的百分比(同一日期的点击/点击数* 100),返回这样的对象:

[
    {
        "_id": {
            "action": "ctr",
            "date": "2015-02-02T00:00:00+01:00"
        },
        "total": 38.46
    },
    {
        "_id": {
            "action": "ctr",
            "date": "2015-02-03T00:00:00+01:00"
        },
        "total": 28
    }
]

任何提示?

1 个答案:

答案 0 :(得分:2)

_.groupBy(array, function(el){ return el._id.date; });

以上是您可以分组的方式,然后您可以映射并计算您需要的内容。例如:

http://jsfiddle.net/j9Htk/114/