繁体   English   中英

使用Lodash无法实现JSON结构

[英]Can't achieve JSON structure using 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/

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

任何帮助将不胜感激!

谢谢!

您只需要在groupBy之后再做一张额外的map就可以得到想要的结构,使用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();

现场演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM