使用Lodash无法实现JSON结构

时间:2014-09-01 17:31:25

标签: javascript json nested chaining lodash

我仍然很难找出使用哪种方法。我正在玩早先给我的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/

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

非常感谢任何帮助!

谢谢!

1 个答案:

答案 0 :(得分:1)

您需要在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