[英]Use Lodash to transform this nested json data
我是lodash的新手。 我有這種json數據。 我已經有90-120行代碼解析它,對它進行一些計算,並創建新的json。 它正在成為一場噩夢。
我想問一下如何使用lodash的方法來改變這個json。
[
{
"dates": [
{
"datetime": "2014-08-26",
"deviceModels": [
{
"deviceModel": "Canon450MX",
"devices": [
{
"deviceModel": "Canon450MX",
"inchesPrinted": 10,
"serialNum" : "111"
},
{
"deviceModel": "Canon450MX",
"inchesPrinted": 10,
"serialNum" : "222"
},
{
"deviceModel": "Canon450MX",
"inchesPrinted": 10,
"serialNum" : "333"
}
]
},
{
"deviceModel": "HPDeskjet",
"devices": [
{
"deviceModel": "HPDeskjet",
"inchesPrinted": 20,
"serialNum" : "444"
},
{
"deviceModel": "HPDeskjet",
"inchesPrinted": 20,
"serialNum" : "555"
}
]
}
]
},
{
"datetime": "2014-08-27",
"deviceModels": [
{
"deviceModel": "Canon450MX",
"devices": [
{
"deviceModel": "Canon450MX",
"inchesPrinted": 5,
"serialNum" : "111"
},
{
"deviceModel": "Canon450MX",
"inchesPrinted": 25,
"serialNum" : "222"
},
{
"deviceModel": "Canon450MX",
"inchesPrinted": 15,
"serialNum" : "333"
}
]
},
{
"deviceModel": "HPDeskjet",
"devices": [
{
"deviceModel": "HPDeskjet",
"inchesPrinted": 10,
"serialNum" : "444"
},
{
"deviceModel": "gx420d",
"inchesPrinted": 20,
"serialNum" : "555"
}
]
}
]
}
]
}
]
我希望新的輸出json是這樣的:
[
{ date : 2014-08-26, deviceModel : 'Canon450MX', totalInchesPrinted : 30 },
{ date : 2014-08-26, deviceModel : 'HPDeskJet', totalInchesPrinted : 40 },
{ date : 2014-08-27, deviceModel : 'Canon450MX', totalInchesPrinted : 45 },
{ date : 2014-08-27, deviceModel : 'HPDeskJet', totalInchesPrinted : 30 }
]
任何幫助將不勝感激!
謝謝!
這應該將數據轉換為所需的形式:
var sumInchesPrinted = function(total, device){
return total + device.inchesPrinted
}
var transformDeviceModels = function(dates){
return _.map(dates.deviceModels, function(deviceModel){
return {
date: dates.datetime,
deviceModel: deviceModel.deviceModel,
totalInchesPrinted: _.reduce(deviceModel.devices, sumInchesPrinted, 0)
}
});
};
var data = _.chain(list[0].dates)
.map(transformDeviceModels)
.flatten()
.value();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.