我有一个查询,可以向我提供Json数据;例如我有以下杰森
{
"salesInvoices":
[
{
"id": "1",
"salesInvoiceLines":
[
{
"ItemCode": "Apple",
"UnitCode": "piece",
"Quantity": "10"
},
{
"ItemCode": "Orange",
"UnitCode": "box",
"Quantity": "2"
}
]
},
{
"id": "2",
"salesInvoiceLines":
[
{
"ItemCode": "Apple",
"UnitCode": "piece",
"Quantity": "20"
},
{
"ItemCode": "Orange",
"UnitCode": "piece",
"Quantity": "21"
},
{
"ItemCode": "Orange",
"UnitCode": "box",
"Quantity": "1"
}
]
}
]
}
我想按项目单位对将数据分组为以下格式:
[
{ item : 'Apple', unit : 'piece', totalQuantity : 30 },
{ item : 'Orange', unit : 'piece', totalQuantity : 21 },
{ item : 'Orange', unit : 'box', totalQuantity : 3 }
]
我用lodash库累了下面的代码,但是不起作用
var sumQuantity = function(total, item){
return total + item.Quantity
}
var transformList = function(line){
return _.map(line.SalesInvoiceLines, function(invoice){
return _.map(invoice, function(line){
return {
item: line.ItemCode,
unit: line.UnitCode,
totalQuantity: _.reduce(line.Quantity, sumQuantity, 0)
}
})
});
};
var groupedList = _.groupBy(data.d.results, function(line) {
return line.ItemCode + line.UnitCode;
});
var list = _.chain(groupedList)
.map(transformList)
.flatten()
.value();
如何获得上述结果?
最佳答案
// Input
var data = {
"salesInvoices": [{
"id": "1",
"salesInvoiceLines": [{
"ItemCode": "Apple",
"UnitCode": "piece",
"Quantity": "10"
}, {
"ItemCode": "Orange",
"UnitCode": "box",
"Quantity": "2"
}]
}, {
"id": "2",
"salesInvoiceLines": [{
"ItemCode": "Apple",
"UnitCode": "piece",
"Quantity": "20"
}, {
"ItemCode": "Orange",
"UnitCode": "piece",
"Quantity": "21"
}, {
"ItemCode": "Orange",
"UnitCode": "box",
"Quantity": "1"
}]
}]
}
//Output
/*
[
{ item : 'Apple', unit : 'piece', totalQuantity : 30 },
{ item : 'Orange', unit : 'piece', totalQuantity : 21 },
{ item : 'Orange', unit : 'box', totalQuantity : 3 }
]
*/
// Code
_.chain(_.flatten(_.map(data.salesInvoices, 'salesInvoiceLines')))
.reduce(function(output, curr) {
output[curr.ItemCode + '_' + curr.UnitCode] = output[curr.ItemCode + '_' + curr.UnitCode] ? output[curr.ItemCode + '_' + curr.UnitCode] + parseInt(curr.Quantity) : parseInt(curr.Quantity);
return output;
}, {})
.reduce(function(result, value, key) {
result.push({
item: key.split('_')[0],
unit: key.split('_')[1],
totalQuantity: value
});
return result;
}, []).value();
关于javascript - 使用lodash转换集合,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34837919/