gpt4 book ai didi

javascript - 无法使用 Lodash 实现 JSON 结构

转载 作者:行者123 更新时间:2023-12-03 11:56:08 27 4
gpt4 key购买 nike

我仍然很难弄清楚要使用哪些方法。我正在使用提供给我的早期 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 Fiddle - http://jsfiddle.net/ohgenLr5/2/

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

任何帮助将不胜感激!

谢谢!

最佳答案

你只需要做一个额外的mapgroupBy 之后得到你想要的结构,使用 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

关于javascript - 无法使用 Lodash 实现 JSON 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25610629/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com