我仍然很难找出要使用的方法。我正在使用提供给我的较早的lodash解决方案,以便可以了解Lodash的工作方式。当前正在发生的事情是,输出变成了一个对象,而deviceModels变成了键。我期待这种输出

[ { "deviceModel": "Canon450MX", "overallTotal": 75, "deviceCount": 3, "dates": [ { "date": "2014-09-01T05:00:00Z", "deviceModel": "Canon450MX", // This can be removed "totalInchesPrinted": 30 }, { "date": "2014-09-01T06:00:00Z", "deviceModel": "Canon450MX", // This can be removed "totalInchesPrinted": 180 }, { "date": "2014-09-01T06:00:00Z", "deviceModel": "Canon450MX", // This can be removed "totalInchesPrinted": 45 } ] }, { "deviceModel": "Canon9000ST", "overallTotal": 645, "deviceCount": 3, "dates": [ { "date": "2014-09-01T06:00:00Z", "deviceModel": "Canon9000ST", // This can be removed "totalInchesPrinted": 600 }, { "date": "2014-09-01T06:00:00Z", "deviceModel": "Canon9000ST", // This can be removed "totalInchesPrinted": 45 } ] }, { "deviceModel": "HPDeskjet", "overallTotal": 76, "deviceCount": 3, "dates": [ { "date": "2014-09-01T05:00:00Z", "deviceModel": "HPDeskjet", // This can be removed "totalInchesPrinted": 40 }, { "date": "2014-09-01T06:00:00Z", "deviceModel": "HPDeskjet", // This can be removed "totalInchesPrinted": 6 }, { "date": "2014-09-01T07:00:00Z", "deviceModel": "HPDeskjet", // This can be removed "totalInchesPrinted": 30 } ] }]

但是输出是这样生成的
{ "Canon450MX": [ { "date": "2014-09-01T05:00:00Z", "deviceModel": "Canon450MX", "totalInchesPrinted": 30 }, { "date": "2014-09-01T06:00:00Z", "deviceModel": "Canon450MX", "totalInchesPrinted": 180 }, { "date": "2014-09-01T07:00:00Z", "deviceModel": "Canon450MX", "totalInchesPrinted": 45 } ], "Canon9000ST": [ { "date": "2014-09-01T06:00:00Z", "deviceModel": "Canon9000ST", "totalInchesPrinted": 600 }, { "date": "2014-09-01T07:00:00Z", "deviceModel": "Canon9000ST", "totalInchesPrinted": 45 } ], "HPDeskjet": [ { "date": "2014-09-01T05:00:00Z", "deviceModel": "HPDeskjet", "totalInchesPrinted": 40 }, { "date": "2014-09-01T06:00:00Z", "deviceModel": "HPDeskjet", "totalInchesPrinted": 6 }, { "date": "2014-09-01T07:00:00Z", "deviceModel": "HPDeskjet", "totalInchesPrinted": 30 } ]}

这是我的JS小提琴-http://jsfiddle.net/ohgenLr5/2/

另外,我想知道如何根据当天的唯一序列号添加totalTotal和deviceCount(如上所示)。

任何帮助将不胜感激!

谢谢!

最佳答案

您只需要在map之后做一个额外的groupBy即可得到所需的结构,使用reduce可以得到打印的总英寸数总和...

var data = _.chain(list[0].dates)
    .map(transformDeviceModels)
    .flatten()
    .sortBy('deviceModel')
    .groupBy('deviceModel')
    .map(function(printers, model) {
        return {
            deviceModel: model,
            overallTotal: _.reduce(printers, function(sum, printer) {
                return sum + printer.totalInchesPrinted;
            }, 0),
            deviceCount: printers.length,
            dates: printers
        };
    })
    .value();


Live Demo

09-28 03:59