我有以下查询,以便选择销售订单行的项目,单位和数量:
var urlBestSoldItemDaily = sharedProperties.fooApi +
"/salesinvoice/SalesInvoices?$expand=SalesInvoiceLines&" +
"$select=SalesInvoiceLines/ItemCode,SalesInvoiceLines/UnitCode,SalesInvoiceLines/Quantity&"
结果是这样的:
<entry>
<id>https://foo/api/salesinvoice/SalesInvoices(guid'607897fa-44aa-4626-a151-1b084bc9d149')</id>
<m:inline>
<feed>
<title type="text">SalesInvoiceLines</title>
<id>https://foo/api/salesinvoice/SalesInvoices(guid'607897fa-44aa-4626-a151-1b084bc9d149')/SalesInvoiceLines</id>
<entry>
<id>https://foo/api/salesinvoice/SalesInvoiceLines(guid'2cdf60c3-3430-4d6c-a58a-b7e96f9d6be6')</id>
<content type="application/xml">
<m:properties>
<d:ItemCode>IND43007</d:ItemCode>
<d:Quantity m:type="Edm.Double">2</d:Quantity>
<d:UnitCode>box</d:UnitCode>
</m:properties>
</content>
</entry>
</feed>
</m:inline>
我想在item-unit上执行分组,然后使用lodash选择按数量排序的结果列表的前10位。我尝试使用以下进行分组,但它不起作用:
var list = _.groupBy(data.d.results, 'SalesInvoiceLines.ItemCode, SalesInvoiceLines.UnitCode');
如何执行分组,以便我有一个分组项目和单位与总数量的集合?
答案 0 :(得分:1)
如何做到这一点的示例:
var sales = [
{itemCode: "0001", quantity: 2, unitItem: "box" },
{itemCode: "0002", quantity: 2, unitItem: "box" },
{itemCode: "0003", quantity: 3, unitItem: "boxx" },
{itemCode: "0004", quantity: 3, unitItem: "boxxx"},
{itemCode: "0005", quantity: 1, unitItem: "boxxx"}
];
/*
* I want to perform grouping on item-unit and then select the top 10
* of the result list sorted by quantity, using lodash.
*/
var calcQuantities = function(sales) {
var sum = function(total, curr) {
return total + curr.quantity;
};
return _.reduce(sales, sum, 0);
};
var toQuantitySale = function(sales) {
return {
quantity: calcQuantities(sales),
sales : sales
};
};
var sortDesc = function(sale) {
return -sale.quantity;
};
// Steps
var groupedSales = _.groupBy(sales, 'unitItem')
var quantitySales = _.map(groupedSales, toQuantitySale)
var sortedSales = _.sortBy(quantitySales, sortDesc)
var top10Sales = _.take(sortedSales, 10)
console.log(top10Sales);
// shorter
top10Sales =
_.chain(sales)
.groupBy('unitItem')
.map(toQuantitySale)
.sortBy(sortDesc)
.take(10)
.value()