Javascript添加缺少的日期时间序列结果

时间:2015-01-29 08:41:47

标签: javascript date underscore.js time-series

我有一个针对Mongodb的聚合操作的结果对象,结果是这样的:

[
    {
        "_id": {
            "action": "hit",
            "date": "2015-01-20T00:00:00.000Z"
        },
        "avg": 3,
        "min": 3,
        "max": 3,
        "total": 3
    },
    {
        "_id": {
            "action": "hit",
            "date": "2015-01-23T00:00:00.000Z"
        },
        "avg": 1,
        "min": 1,
        "max": 1,
        "total": 12
    }
]

我需要添加零值的缺失日期,例如,如果我要求从1月20日开始的一周范围,我想要一个这样的结果对象:

[
    {
        "_id": {
            "action": "hit",
            "date": "2015-01-20T00:00:00.000Z"
        },
        "avg": 3,
        "min": 3,
        "max": 3,
        "total": 3
    },
    {
        "_id": {
            "action": "hit",
            "date": "2015-01-21T00:00:00.000Z"
        },
        "avg": 0,
        "min": 0,
        "max": 0,
        "total": 0
    },
    {
        "_id": {
            "action": "hit",
            "date": "2015-01-22T00:00:00.000Z"
        },
        "avg": 0,
        "min": 0,
        "max": 0,
        "total": 0
    },
    {
        "_id": {
            "action": "hit",
            "date": "2015-01-23T00:00:00.000Z"
        },
        "avg": 1,
        "min": 1,
        "max": 1,
        "total": 12
    },
    {...}
]

包含日期范围的数组是:

[ 
"2015-01-20T00:00:00.000Z",
"2015-01-21T00:00:00.000Z",
"2015-01-22T00:00:00.000Z",
"2015-01-23T00:00:00.000Z",
"2015-01-24T00:00:00.000Z",
"2015-01-25T00:00:00.000Z",
"2015-01-26T00:00:00.000Z",
]

对于此数组中的每个日期,我必须在之前的结果中添加零值对象。

我尝试使用下划线和map / reduce / clone但我无法获得正确的结果。

请帮忙吗?

1 个答案:

答案 0 :(得分:1)

我做到了,但我想念零值,我现在就要这样做。

        var cloneItem = {};

        // Generate the date range arrays with single days
        var range = moment().range(new Date(req.query.datefrom), new Date(req.query.dateto)),
            days = [];
        range.by('days', function(moment) {
            days.push(moment.startOf('day').format());
        });

        // Rewrite dates to match the same date range format from the array above
        webstat = _.map(webstat, function (value, key, list) {
            value._id.date = moment(value._id.date).startOf('day').format();
            if (key === 0) cloneItem = value;
            return value;
        });

        // Add the object values when they are missed               
        days.forEach(function (day) {
            var clone = _.extend({}, cloneItem, {_id: {action: cloneItem._id.action, date: day}});

            if (_.findWhere(webstat, {_id: { date: day}}) === undefined) {
                webstat.push(clone);
            }
        });

        // Sort by date and send it
        res.jsonp(
            _.sortBy(webstat, function (item) {
                return item._id.date;
            })
        );